/* global React, Icons, SECTION_DEFS, Field, AutoText */
// ============================================================
//  Section organizer (drag & drop "segments") + editors for the
//  extra section types. Lets the user pick, drop, reorder and
//  remove résumé segments. Order is stored on resume.sectionOrder.
// ============================================================
const { useState: useStateSE, useRef: useRefSE } = React;

function uidSE() { return Math.random().toString(36).slice(2, 9); }

// sensible starter content when a brand-new segment is added
const SECTION_STARTERS = {
  summary: () => ({ summary: "" }),
  experience: () => ({ experience: [{ id: uidSE(), role: "Role", company: "Company", start: "2024", end: "Present", location: "", bullets: ["Describe what you did and the impact."] }] }),
  projects: () => ({ projects: [{ id: uidSE(), name: "Project name", desc: "What it is and why it matters." }] }),
  education: () => ({ education: [{ id: uidSE(), school: "School", degree: "Degree", start: "2020", end: "2024" }] }),
  skills: () => ({ skills: [{ name: "Skill", level: 3 }] }),
  certifications: () => ({ certifications: [{ id: uidSE(), name: "Certification", issuer: "Issuer", year: "2024" }] }),
  awards: () => ({ awards: [{ id: uidSE(), name: "Award", issuer: "", year: "2024" }] }),
  languages: () => ({ languages: [{ id: uidSE(), name: "Language", level: "Professional" }] }),
  publications: () => ({ publications: [{ id: uidSE(), title: "Publication title", venue: "Venue", year: "2024" }] }),
  volunteer: () => ({ volunteer: [{ id: uidSE(), role: "Role", company: "Organization", start: "2022", end: "Present", location: "", bullets: ["What you contributed."] }] }),
  courses: () => ({ courses: ["Course name"] }),
  interests: () => ({ interests: ["Interest"] }),
  references: () => ({ references: [{ id: uidSE(), name: "Reference name", title: "Title, Company", contact: "email@example.com" }] }),
};

const DEFAULT_VISIBLE = ["summary", "experience", "projects", "skills", "certifications", "awards", "languages", "education"];

// the order to show when a résumé has no explicit sectionOrder yet:
// the default segments that actually have content (matches the preview)
function effectiveOrder(resume) {
  if (resume.sectionOrder && resume.sectionOrder.length) return resume.sectionOrder;
  const has = window.sectionHasData || (() => true);
  const base = DEFAULT_VISIBLE.filter((k) => has(k, resume));
  return base.length ? base : DEFAULT_VISIBLE.slice(0, 4);
}

// ---------- the drag & drop organizer ----------
function SectionOrganizer({ resume, setResume }) {
  const order = effectiveOrder(resume);
  const setOrder = (o) => setResume((r) => ({ ...r, sectionOrder: o }));
  const drag = useRefSE(null);
  const [overKey, setOverKey] = useStateSE(null);
  const [dropActive, setDropActive] = useStateSE(false);

  const inactive = Object.keys(SECTION_DEFS).filter((k) => !order.includes(k));

  const seed = (k) => {
    const starter = SECTION_STARTERS[k];
    if (!starter) return;
    setResume((r) => {
      const empty = (k === "summary") ? !(r.summary && r.summary.trim()) : !(Array.isArray(r[k]) && r[k].length);
      return empty ? { ...r, ...starter() } : r;
    });
  };

  const addSection = (k) => { seed(k); if (!order.includes(k)) setOrder([...order, k]); };
  const removeSection = (k) => setOrder(order.filter((x) => x !== k));

  const onRowDragStart = (k) => (e) => { drag.current = { k, from: "list" }; e.dataTransfer.effectAllowed = "move"; try { e.dataTransfer.setData("text/plain", k); } catch (_) {} };
  const onPalDragStart = (k) => (e) => { drag.current = { k, from: "pal" }; e.dataTransfer.effectAllowed = "copy"; try { e.dataTransfer.setData("text/plain", k); } catch (_) {} };

  const onRowDragOver = (k) => (e) => {
    e.preventDefault();
    const d = drag.current; if (!d) return;
    setOverKey(k);
    if (d.from !== "list" || d.k === k) return;
    const o = [...order];
    const from = o.indexOf(d.k); const to = o.indexOf(k);
    if (from < 0 || to < 0) return;
    o.splice(from, 1); o.splice(to, 0, d.k);
    setOrder(o);
  };

  const onListDrop = (e) => {
    e.preventDefault();
    const d = drag.current;
    if (d && d.from === "pal" && !order.includes(d.k)) addSection(d.k);
    drag.current = null; setOverKey(null); setDropActive(false);
  };
  const onDragEnd = () => { drag.current = null; setOverKey(null); setDropActive(false); };

  return (
    <div className="org">
      <p className="org-hint">Drag segments to reorder how they appear on your résumé. Add or remove the ones relevant to you.</p>
      <div
        className={`org-list ${dropActive ? "drop" : ""}`}
        onDragOver={(e) => { if (drag.current && drag.current.from === "pal") { e.preventDefault(); setDropActive(true); } }}
        onDragLeave={(e) => { if (e.currentTarget === e.target) setDropActive(false); }}
        onDrop={onListDrop}
      >
        {order.filter((k) => SECTION_DEFS[k]).map((k) => {
          const def = SECTION_DEFS[k];
          const Ic = Icons[def.icon] || Icons.tag;
          return (
            <div
              key={k}
              className={`org-row ${overKey === k ? "over" : ""}`}
              draggable
              onDragStart={onRowDragStart(k)}
              onDragOver={onRowDragOver(k)}
              onDragEnd={onDragEnd}
              onDrop={onListDrop}
            >
              <span className="org-grip"><Icons.grip size={16} /></span>
              <span className="org-ic"><Ic size={15} /></span>
              <span className="org-label">{def.label}</span>
              <span className="org-blurb">{def.blurb}</span>
              <button className="org-x" title="Remove from résumé" onClick={() => removeSection(k)}><Icons.close size={14} /></button>
            </div>
          );
        })}
      </div>

      {inactive.length > 0 && (
        <>
          <div className="org-add-t">Add a segment</div>
          <div className="org-pal">
            {inactive.map((k) => {
              const def = SECTION_DEFS[k];
              const Ic = Icons[def.icon] || Icons.tag;
              return (
                <button key={k} className="org-chip" draggable onDragStart={onPalDragStart(k)} onDragEnd={onDragEnd} onClick={() => addSection(k)}>
                  <span className="org-chip-ic"><Ic size={14} /></span>
                  <span>{def.label}</span>
                  <Icons.plus size={13} />
                </button>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

// ---------- editors for the extra section types ----------
function CardRow({ onDelete, children }) {
  return (
    <div className="card-edit">
      <div className="card-edit-top">
        <span className="drag-h"><Icons.drag size={16} /></span>
        <button className="del-btn" onClick={onDelete} title="Remove"><Icons.trash size={14} /></button>
      </div>
      {children}
    </div>
  );
}

function NamedEditor({ items, onChange, nameLabel, addLabel }) {
  const set = (id, patch) => onChange(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  return (
    <>
      {(items || []).map((it) => (
        <CardRow key={it.id} onDelete={() => onChange(items.filter((x) => x.id !== it.id))}>
          <Field label={nameLabel} value={it.name} onChange={(v) => set(it.id, { name: v })} />
          <div className="grid-2">
            <Field label="Issuer / org" value={it.issuer} onChange={(v) => set(it.id, { issuer: v })} />
            <Field label="Year" value={it.year} onChange={(v) => set(it.id, { year: v })} mono />
          </div>
        </CardRow>
      ))}
      <button className="add-card" onClick={() => onChange([...(items || []), { id: uidSE(), name: "", issuer: "", year: "" }])}><Icons.plus size={15} /> {addLabel}</button>
    </>
  );
}

function LanguageEditor({ items, onChange }) {
  const set = (id, patch) => onChange(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  const LEVELS = ["Native", "Fluent", "Professional", "Conversational", "Basic"];
  return (
    <>
      {(items || []).map((it) => (
        <CardRow key={it.id} onDelete={() => onChange(items.filter((x) => x.id !== it.id))}>
          <div className="grid-2">
            <Field label="Language" value={it.name} onChange={(v) => set(it.id, { name: v })} />
            <label className="field">
              <span className="field-l">Proficiency</span>
              <select className="fld" value={it.level} onChange={(e) => set(it.id, { level: e.target.value })}>
                {LEVELS.map((l) => <option key={l} value={l}>{l}</option>)}
              </select>
            </label>
          </div>
        </CardRow>
      ))}
      <button className="add-card" onClick={() => onChange([...(items || []), { id: uidSE(), name: "", level: "Professional" }])}><Icons.plus size={15} /> Add language</button>
    </>
  );
}

function PublicationEditor({ items, onChange }) {
  const set = (id, patch) => onChange(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  return (
    <>
      {(items || []).map((it) => (
        <CardRow key={it.id} onDelete={() => onChange(items.filter((x) => x.id !== it.id))}>
          <Field label="Title" value={it.title} onChange={(v) => set(it.id, { title: v })} />
          <div className="grid-2">
            <Field label="Venue / journal" value={it.venue} onChange={(v) => set(it.id, { venue: v })} />
            <Field label="Year" value={it.year} onChange={(v) => set(it.id, { year: v })} mono />
          </div>
        </CardRow>
      ))}
      <button className="add-card" onClick={() => onChange([...(items || []), { id: uidSE(), title: "", venue: "", year: "" }])}><Icons.plus size={15} /> Add publication</button>
    </>
  );
}

function ReferenceEditor({ items, onChange }) {
  const set = (id, patch) => onChange(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  return (
    <>
      {(items || []).map((it) => (
        <CardRow key={it.id} onDelete={() => onChange(items.filter((x) => x.id !== it.id))}>
          <Field label="Name" value={it.name} onChange={(v) => set(it.id, { name: v })} />
          <Field label="Title & company" value={it.title} onChange={(v) => set(it.id, { title: v })} />
          <Field label="Contact" value={it.contact} onChange={(v) => set(it.id, { contact: v })} />
        </CardRow>
      ))}
      <button className="add-card" onClick={() => onChange([...(items || []), { id: uidSE(), name: "", title: "", contact: "" }])}><Icons.plus size={15} /> Add reference</button>
    </>
  );
}

function ProjectEditor({ items, onChange }) {
  const set = (id, patch) => onChange(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  return (
    <>
      {(items || []).map((it) => (
        <CardRow key={it.id} onDelete={() => onChange(items.filter((x) => x.id !== it.id))}>
          <Field label="Project" value={it.name} onChange={(v) => set(it.id, { name: v })} />
          <label className="field">
            <span className="field-l">Description</span>
            <AutoText value={it.desc} onChange={(v) => set(it.id, { desc: v })} placeholder="What it is and the impact." />
          </label>
        </CardRow>
      ))}
      <button className="add-card" onClick={() => onChange([...(items || []), { id: uidSE(), name: "", desc: "" }])}><Icons.plus size={15} /> Add project</button>
    </>
  );
}

function VolunteerEditor({ items, onChange }) {
  const set = (id, patch) => onChange(items.map((it) => it.id === id ? { ...it, ...patch } : it));
  const setBullet = (id, i, v) => { const it = items.find((x) => x.id === id); set(id, { bullets: it.bullets.map((b, j) => j === i ? v : b) }); };
  return (
    <>
      {(items || []).map((it) => (
        <CardRow key={it.id} onDelete={() => onChange(items.filter((x) => x.id !== it.id))}>
          <Field label="Role" value={it.role} onChange={(v) => set(it.id, { role: v })} />
          <div className="grid-2">
            <Field label="Organization" value={it.company} onChange={(v) => set(it.id, { company: v })} />
            <Field label="Years" value={`${it.start} – ${it.end}`} onChange={(v) => { const [s, e] = v.split("–").map((x) => x.trim()); set(it.id, { start: s || "", end: e || "" }); }} mono />
          </div>
          <span className="field-l" style={{ marginTop: 6 }}>Highlights</span>
          {(it.bullets || []).map((b, i) => (
            <div className="bullet-row" key={i}>
              <span className="bullet-dot" />
              <AutoText value={b} onChange={(v) => setBullet(it.id, i, v)} placeholder="What you contributed…" />
              <button className="bul-del" onClick={() => set(it.id, { bullets: it.bullets.filter((_, j) => j !== i) })}><Icons.close size={13} /></button>
            </div>
          ))}
          <button className="add-inline" onClick={() => set(it.id, { bullets: [...(it.bullets || []), ""] })}><Icons.plus size={13} /> Add highlight</button>
        </CardRow>
      ))}
      <button className="add-card" onClick={() => onChange([...(items || []), { id: uidSE(), role: "", company: "", start: "", end: "", location: "", bullets: [""] }])}><Icons.plus size={15} /> Add entry</button>
    </>
  );
}

function ChipEditor({ items, onChange, placeholder }) {
  const [draft, setDraft] = useStateSE("");
  const add = () => { const v = draft.trim(); if (v) { onChange([...(items || []), v]); setDraft(""); } };
  return (
    <>
      <div className="skill-tags">
        {(items || []).map((s, i) => (
          <span className="skill-tag" key={i}>{s}<button onClick={() => onChange(items.filter((_, x) => x !== i))}><Icons.close size={12} /></button></span>
        ))}
      </div>
      <div className="skill-add">
        <input className="fld" value={draft} placeholder={placeholder}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
        <button className="btn btn-ghost btn-sm" onClick={add}><Icons.plus size={14} /></button>
      </div>
    </>
  );
}

// map a section key to its editor (only the "extra" ones — core ones live in Builder)
function ExtraSectionEditor({ k, resume, setResume }) {
  const set = (key, val) => setResume((r) => ({ ...r, [key]: val }));
  switch (k) {
    case "projects": return <ProjectEditor items={resume.projects} onChange={(v) => set("projects", v)} />;
    case "certifications": return <NamedEditor items={resume.certifications} onChange={(v) => set("certifications", v)} nameLabel="Certification" addLabel="Add certification" />;
    case "awards": return <NamedEditor items={resume.awards} onChange={(v) => set("awards", v)} nameLabel="Award" addLabel="Add award" />;
    case "languages": return <LanguageEditor items={resume.languages} onChange={(v) => set("languages", v)} />;
    case "publications": return <PublicationEditor items={resume.publications} onChange={(v) => set("publications", v)} />;
    case "volunteer": return <VolunteerEditor items={resume.volunteer} onChange={(v) => set("volunteer", v)} />;
    case "references": return <ReferenceEditor items={resume.references} onChange={(v) => set("references", v)} />;
    case "courses": return <ChipEditor items={resume.courses} onChange={(v) => set("courses", v)} placeholder="Add a course and press Enter" />;
    case "interests": return <ChipEditor items={resume.interests} onChange={(v) => set("interests", v)} placeholder="Add an interest and press Enter" />;
    default: return null;
  }
}

const EXTRA_KEYS = ["projects", "certifications", "awards", "languages", "publications", "volunteer", "courses", "interests", "references"];

Object.assign(window, { SectionOrganizer, ExtraSectionEditor, EXTRA_KEYS, DEFAULT_VISIBLE, effectiveOrder });
