/* ============================================================
   Edit Mode — warning banner + per-window settings panels.
   Edits apply live to the store; "Save" confirms.
   ============================================================ */
const { useState: uSe, useEffect: uEe } = React;

/* small generic helpers ---------------------------------- */
function NameModal({ title, label, initial, onClose, onSave }) {
  const [v, setV] = uSe(initial || "");
  return (
    <Modal title={title} onClose={onClose}
      footer={<><button className="btn ghost" onClick={onClose}>Cancel</button><button className="btn accent" onClick={() => v.trim() && onSave(v.trim())}>Add</button></>}>
      <div><label>{label}</label><input autoFocus value={v} onChange={e => setV(e.target.value)} onKeyDown={e => e.key === "Enter" && v.trim() && onSave(v.trim())} /></div>
    </Modal>
  );
}

function MultiSelect({ options, selected, onToggle }) {
  return (
    <div className="multi">
      {options.map(o => (
        <button key={o.id} className={"chip opt" + (selected.includes(o.id) ? " on" : "")} onClick={() => onToggle(o.id)}>
          {selected.includes(o.id) && <Icon name="check" size={12} style={{ verticalAlign: "-2px", marginRight: 3 }} />}{o.label}
        </button>
      ))}
    </div>
  );
}

function ToggleRow({ label, sub, on, onChange, color }) {
  return (
    <div className="dragrow" style={{ cursor: "default" }}>
      {color && <span style={{ width: 12, height: 12, borderRadius: 4, background: color, flex: "none" }} />}
      <span className="nm">{label}{sub && <span className="dim mono" style={{ fontSize: 11, fontWeight: 400, marginLeft: 8 }}>{sub}</span>}</span>
      <button className={"toggle" + (on ? " on" : "")} onClick={() => onChange(!on)} />
    </div>
  );
}

function EditSection({ num, title, children }) {
  return (
    <div className="edit-section">
      <div className="es-title"><span className="es-num">{num}</span>{title}</div>
      {children}
    </div>
  );
}

/* ---- social network editor modal (home, full def) ---- */
function SocialModal({ data, domains, onClose, onSave, onDelete }) {
  const [s, setS] = uSe(data.social);
  const COLORS = ["#0a66c2", "#211e1a", "#e1543f", "#d62976", "#1f9e72", "#7a4fe0"];
  return (
    <Modal title={data.mode === "add" ? "New social network" : "Edit social network"} onClose={onClose}
      footer={<>
        {data.mode === "edit" && <button className="btn ghost" style={{ color: "var(--c-coral)", marginRight: "auto" }} onClick={() => { onDelete(s.id); onClose(); }}><Icon name="trash" size={16} /> Delete</button>}
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn accent" onClick={() => s.name.trim() && onSave(s)}><Icon name="save" size={16} /> Save</button>
      </>}>
      <div className="field-row">
        <div><label>Name</label><input value={s.name} onChange={e => setS(p => ({ ...p, name: e.target.value }))} placeholder="LinkedIn" /></div>
        <div><label>Logo</label><div className="ph" style={{ height: 40, fontSize: 11 }}>upload logo<span className="ph-tag">img</span></div></div>
      </div>
      <div><label>Link</label><input value={s.link} onChange={e => setS(p => ({ ...p, link: e.target.value }))} placeholder="https://…" /></div>
      <div><label>Colour</label><div className="row gap-8">{COLORS.map(c => <button key={c} onClick={() => setS(p => ({ ...p, color: c }))} style={{ width: 28, height: 28, borderRadius: 8, background: c, border: s.color === c ? "3px solid var(--ink)" : "1.5px solid var(--line)" }} />)}</div></div>
      <div className="src-note" style={{ marginTop: 4 }}><span className="dim" style={{ fontSize: 12.5 }}>Where this network appears is chosen per domain — open a domain's <b>Window 1 → Social networks</b> to show or hide it there.</span></div>
    </Modal>
  );
}

/* ---- app editor modal (footer apps) ---- */
function AppModal({ data, onClose, onSave, onDelete }) {
  const [a, setA] = uSe(data.app);
  const COLORS = ["#211e1a", "#2f6bdb", "#e1543f", "#7a4fe0", "#1f9e72", "#e08a1e"];
  return (
    <Modal title={data.mode === "add" ? "New app" : "Edit app"} onClose={onClose}
      footer={<>
        {data.mode === "edit" && <button className="btn ghost" style={{ color: "var(--c-coral)", marginRight: "auto" }} onClick={() => { onDelete(a.id); onClose(); }}><Icon name="trash" size={16} /> Delete</button>}
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn accent" onClick={() => a.name.trim() && onSave(a)}><Icon name="save" size={16} /> Save</button>
      </>}>
      <div className="field-row" style={{ alignItems: "flex-start" }}>
        <div style={{ flex: 1 }}>
          <div><label>Title</label><input value={a.name} onChange={e => setA(p => ({ ...p, name: e.target.value }))} placeholder="Notion" /></div>
          <div style={{ marginTop: 10 }}><label>Glyph (fallback)</label><input maxLength={2} value={a.glyph} onChange={e => setA(p => ({ ...p, glyph: e.target.value }))} /></div>
        </div>
        <div style={{ flex: ".7" }}><label>Logo</label><ImageUpload value={a.logo} onChange={v => setA(p => ({ ...p, logo: v }))} label="upload logo" height={86} /></div>
      </div>
      <div><label>Description</label><textarea rows={2} value={a.desc || ""} onChange={e => setA(p => ({ ...p, desc: e.target.value }))} placeholder="What is this app for?" /></div>
      <div><label>Link</label><input value={a.link} onChange={e => setA(p => ({ ...p, link: e.target.value }))} placeholder="https://…" /></div>
      <div><label>Colour</label><div className="row gap-8">{COLORS.map(c => <button key={c} onClick={() => setA(p => ({ ...p, color: c }))} style={{ width: 28, height: 28, borderRadius: 8, background: c, border: a.color === c ? "3px solid var(--ink)" : "1.5px solid var(--line)" }} />)}</div></div>
      <div><label>Visibility</label>
        <div className="row between" style={{ background: "var(--paper-2)", borderRadius: "var(--r-sm)", padding: "9px 13px" }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: a.published === false ? "#b56b08" : "var(--c-green)" }}>{a.published === false ? "Draft — hidden from the site" : "Published — visible"}</span>
          <button className={"toggle" + (a.published !== false ? " on" : "")} onClick={() => setA(p => ({ ...p, published: !(p.published !== false) }))} />
        </div>
      </div>
    </Modal>
  );
}

/* ---- section editor modal (EN + FR names, logo, kind — set at creation) ---- */
function SectionModal({ data, onClose, onSave, onDelete }) {
  const [s, setS] = uSe({ ...data.section, tr: data.section.tr ? JSON.parse(JSON.stringify(data.section.tr)) : {} });
  const setFr = (v) => setS(p => ({ ...p, tr: { ...(p.tr || {}), fr: { ...((p.tr || {}).fr || {}), label: v } } }));
  const TYPES = window.SECTION_TYPE_ORDER.map(id => window.SECTION_TYPES[id]);
  const isAdd = data.mode === "add";
  const curType = s.type || window.sectionTypeOf(s);
  const curTypeMeta = window.SECTION_TYPES[curType] || TYPES[0];
  const pickType = (t) => setS(p => ({ ...p, type: t.id, kind: t.kind }));
  const frLabel = (s.tr && s.tr.fr && s.tr.fr.label) || "";
  // both languages are mandatory at creation; the route/kind are then frozen.
  const canSave = isAdd ? (s.label.trim() && frLabel.trim()) : s.label.trim();
  return (
    <Modal title={isAdd ? "New section" : "Edit section"} onClose={onClose}
      footer={<>
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn accent" disabled={!canSave} style={{ opacity: canSave ? 1 : .5 }} onClick={() => canSave && onSave(s)}><Icon name="save" size={16} /> Save</button>
      </>}>
      <p className="dim" style={{ fontSize: 13, marginTop: -4 }}>{isAdd
        ? <>Pick the section's <b>type</b> — it decides what each piece looks like and which fields are pre-filled when you create content. Set the name in <b>both languages</b> (required) and a <b>route</b>. Type &amp; route are then frozen.</>
        : <>Edit the <b>names</b> and <b>logo</b>. The type and route are fixed — they're the section's permanent identity.</>}</p>
      {isAdd && (
        <div style={{ marginBottom: 4 }}>
          <label>Section type</label>
          <div className="sectype-grid">
            {TYPES.map(t => (
              <button type="button" key={t.id} className={"sectype-card" + (curType === t.id ? " on" : "")} onClick={() => pickType(t)}>
                <span className="st-ic"><Icon name={t.icon} size={18} /></span>
                <span className="st-l">{t.label}</span>
                <span className="st-b">{t.blurb}</span>
              </button>
            ))}
          </div>
        </div>
      )}
      <div className="field-row">
        <div><label>Name · EN {isAdd && <span style={{ color: "var(--c-coral)" }}>*</span>}</label><input autoFocus value={s.label} onChange={e => setS(p => ({ ...p, label: e.target.value }))} placeholder="Blog" /></div>
        <div><label>Name · FR {isAdd && <span style={{ color: "var(--c-coral)" }}>*</span>}</label><input value={frLabel} onChange={e => setFr(e.target.value)} placeholder="Blog" /></div>
      </div>
      <div className="field-row" style={{ alignItems: "flex-start" }}>
        <div style={{ flex: 1 }}>
          {isAdd ? (
            <div style={{ marginTop: 10 }}><label>Route</label><input value={s.route} onChange={e => setS(p => ({ ...p, route: e.target.value }))} placeholder="/blog" /></div>
          ) : (
            <div className="frozen-id">
              <div className="row between"><span className="dim mono" style={{ fontSize: 11 }}>TYPE</span><span style={{ fontWeight: 700, fontFamily: "var(--font-display)" }}>{curTypeMeta.label}</span></div>
              <div className="row between" style={{ marginTop: 8 }}><span className="dim mono" style={{ fontSize: 11 }}>ROUTE</span><span className="mono" style={{ fontSize: 13 }}>{s.route}</span></div>
              <div className="dim" style={{ fontSize: 11.5, marginTop: 9, lineHeight: 1.45 }}><Icon name="lock" size={12} style={{ verticalAlign: "-2px", marginRight: 3 }} />Locked. The route is referenced by the menu, every piece's URL under it, and any embedded / shared links — changing it would break them.</div>
            </div>
          )}
        </div>
        <div style={{ flex: ".75" }}><label>Logo</label><ImageUpload value={s.logo} onChange={v => setS(p => ({ ...p, logo: v }))} label="upload logo" height={92} /></div>
      </div>
    </Modal>
  );
}

/* ---- "Other" pages editor modal ---- */
function OtherPagesModal({ pages, onClose, onChange }) {
  const [list, setList] = uSe(pages.map(p => ({ ...p })));
  const setP = (i, k, v) => setList(l => l.map((p, j) => j === i ? { ...p, [k]: v } : p));
  return (
    <Modal title="Other — created pages" onClose={onClose}
      footer={<><button className="btn ghost" onClick={onClose}>Cancel</button><button className="btn accent" onClick={() => { onChange(list); onClose(); }}><Icon name="save" size={16} /> Save</button></>}>
      <p className="dim" style={{ fontSize: 13, marginTop: -4 }}>Pages like CV, surveys or games. They are <b>not</b> shown in the public Sections menu — link them from a domain or unlock them via a puzzle.</p>
      <div className="col gap-8">
        {list.map((p, i) => (
          <div key={p.id} className="dragrow" style={{ cursor: "default", flexWrap: "wrap", gap: 8 }}>
            <span className="logo" style={{ width: 26, height: 26, borderRadius: 8, background: p.kind === "secret" ? "var(--c-violet)" : "var(--accent)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={p.kind === "secret" ? "lock" : "edit"} size={13} /></span>
            <input style={{ flex: 1, minWidth: 120 }} value={p.label} onChange={e => setP(i, "label", e.target.value)} placeholder="Title" />
            <input style={{ flex: 1, minWidth: 120 }} value={p.route} onChange={e => setP(i, "route", e.target.value)} placeholder="/route" />
            {p.kind !== "secret" && <button className="iconbtn danger" style={{ flex: "none" }} onClick={() => setList(l => l.filter((_, j) => j !== i))}><Icon name="trash" size={15} /></button>}
          </div>
        ))}
      </div>
      <button className="btn ghost sm" style={{ marginTop: 10, alignSelf: "flex-start" }} onClick={() => setList(l => [...l, { id: uid("pg"), label: "New page", route: "/other/new", kind: "page", desc: "" }])}><Icon name="plus" size={15} /> Add page</button>
    </Modal>
  );
}

/* =================== HOME panels =================== */
function HomeEditPanel({ activeWin }) {
  const { db, update } = useStore();
  const { go, lang } = useNav();
  const ed = window.useEdit ? window.useEdit() : {};
  // open a domain's own page editor: navigate to it AND switch the panel to page mode
  const editDomain = (route) => { go(route); if (ed.setPanelMode) ed.setPanelMode("page"); if (ed.setPanelOpen) ed.setPanelOpen(true); };
  const [modal, setModal] = uSe(null); // single modal at a time: { kind, data }
  const close = () => setModal(null);

  const addDomain = (label) => {
    const id = label.toLowerCase().replace(/[^a-z0-9]+/g, "").slice(0, 16) || uid("dom");
    update(d => d.domains.push({ id, route: "/" + id, label, title: "a " + label, display: true, art: "network", presTitle: "the " + label, quote: "Add a quote…", presBody: "Describe this domain…", presImage: null, puzzle: null, sections: ["blog"], extraPages: [], socials: [], featured: [] }));
    close();
  };
  const saveSection = (s) => {
    if (modal && modal.kind === "section" && modal.data.mode === "add") {
      const id = (s.label || "sec").toLowerCase().replace(/[^a-z0-9]+/g, "").slice(0, 16) || uid("sec");
      update(d => d.sections.push({ ...s, id, type: s.type || window.sectionTypeOf(s), route: s.route || "/" + id, inMenu: s.inMenu !== false, logo: s.logo || null, tr: s.tr || {} }));
    } else {
      update(d => { const i = d.sections.findIndex(x => x.id === s.id); if (i >= 0) d.sections[i] = { ...d.sections[i], ...s }; });
    }
    close();
  };

  let body;
  if (activeWin === 2) {
    body = <EmptyPanel msg="The About window on the home page isn't configured here — it follows whichever domain the home points to." />;
  } else if (activeWin === 3) {
    body = (
      <>
        <EditSection num={1} title="APPS block">
          <DragList items={db.apps} onReorder={n => update(d => d.apps = n)} renderRow={(a) => (
            <>
              <span className="logo" style={{ width: 28, height: 28, borderRadius: 8, background: a.logo ? "#fff" : a.color, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, flex: "none", overflow: "hidden" }}>{a.logo ? <img src={a.logo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : a.glyph}</span>
              <span className="nm">{a.name}{a.desc && <span className="dim mono" style={{ fontSize: 11, fontWeight: 400, marginLeft: 8 }}>{a.desc}</span>}{a.published === false && <span className="chip" style={{ marginLeft: 8, borderColor: "var(--c-amber)", color: "#b56b08", fontWeight: 700 }}>Draft</span>}</span>
              <div className="edit-row-tools">
                <button className="iconbtn" onClick={() => setModal({ kind: "app", data: { mode: "edit", app: { ...a } } })}><Icon name="edit" size={15} /></button>
                <button className="iconbtn danger" onClick={() => update(d => d.apps = d.apps.filter(x => x.id !== a.id))}><Icon name="trash" size={15} /></button>
              </div>
            </>
          )} />
          <button className="btn ghost sm" style={{ marginTop: 10 }} onClick={() => setModal({ kind: "app", data: { mode: "add", app: { name: "", glyph: "A", color: "#211e1a", link: "", desc: "", logo: null, published: true } } })}><Icon name="plus" size={15} /> Add an app</button>
        </EditSection>

        <EditSection num={2} title="Navigation block">
          <p className="dim" style={{ fontSize: 13, marginTop: -4, marginBottom: 10 }}>Choose which domains &amp; sections appear in the footer navigation plan.</p>
          <label>Domains</label>
          <div className="draglist" style={{ marginBottom: 14 }}>
            {db.domains.map(d => <ToggleRow key={d.id} label={d.label} color={accentFor(d.id).accent} on={d.display} onChange={v => update(s => { const x = s.domains.find(z => z.id === d.id); x.display = v; })} />)}
          </div>
          <label>Sections</label>
          <div className="draglist">
            {db.sections.map(s => <ToggleRow key={s.id} label={s.label} sub={"/" + s.id} on={s.inMenu} onChange={v => update(z => { const x = z.sections.find(q => q.id === s.id); x.inMenu = v; })} />)}
          </div>
        </EditSection>

        <EditSection num={3} title="Legal pages">
          <p className="dim" style={{ fontSize: 13, marginTop: -4, marginBottom: 12 }}>The footer's legal pages. Open <b>Manage content</b> to edit each one on its own page — title and body, in both languages (EN/FR).</p>
          <div className="col gap-8">
            {[{ k: "cgu", r: "/legal/cgu" }, { k: "mentions", r: "/legal/mentions" }, { k: "copyright", r: "/legal/copyright" }].map(({ k, r }) => {
              const lp = (db.legal && db.legal[k]) || (window.LEGAL_SEED && window.LEGAL_SEED[k]) || { title: "", body: "" };
              return (
                <div key={k} className="dragrow" style={{ cursor: "default" }}>
                  <span className="sec-row-logo" style={{ background: "var(--accent)" }}><Icon name="edit" size={14} /></span>
                  <span className="nm">{lp.title} <span className="dim mono" style={{ fontSize: 11, fontWeight: 400 }}>{r}</span></span>
                  <button className="btn ghost sm" style={{ flex: "none" }} onClick={() => go(r)}><Icon name="arrow" size={14} /> Manage content</button>
                </div>
              );
            })}
          </div>
        </EditSection>
      </>
    );
  } else {
    // window 1 (home)
    body = (
      <>
        <EditSection num={1} title="Home target route">
          <p className="dim" style={{ fontSize: 13, marginTop: -4, marginBottom: 10 }}>Which domain the home page (index) points to.</p>
          <select value={db.profile.defaultRoute} onChange={e => update(d => d.profile.defaultRoute = e.target.value)}>
            {db.domains.filter(d => d.display).map(d => <option key={d.id} value={d.route}>{d.route} — {d.label}</option>)}
          </select>
        </EditSection>

        <EditSection num={2} title="Domains (ordered)">
          <DragList items={db.domains} onReorder={n => update(d => d.domains = n)} renderRow={(dm) => (
            <>
              <span style={{ width: 12, height: 12, borderRadius: 4, background: accentFor(dm.id).accent, flex: "none" }} />
              <span className="nm" style={{ cursor: "pointer" }} onClick={() => editDomain(dm.route)}>{dm.label} <span className="dim mono" style={{ fontSize: 11 }}>{dm.route}</span></span>
              <div className="edit-row-tools">
                <button className={"toggle" + (dm.display ? " on" : "")} onClick={() => update(d => { d.domains.find(x => x.id === dm.id).display = !dm.display; })} />
                <button className="iconbtn" title="edit domain" onClick={() => editDomain(dm.route)}><Icon name="arrow" size={15} /></button>
                <button className="iconbtn danger" onClick={() => update(d => d.domains = d.domains.filter(x => x.id !== dm.id))}><Icon name="trash" size={15} /></button>
              </div>
            </>
          )} />
          <button className="btn ghost sm" style={{ marginTop: 10 }} onClick={() => setModal({ kind: "addDomain" })}><Icon name="plus" size={15} /> Add domain</button>
        </EditSection>

        <EditSection num={3} title="Social networks (defined here)">
          <DragList items={db.socials} onReorder={n => update(d => d.socials = n)} renderRow={(s) => (
            <>
              <span className="logo" style={{ width: 26, height: 26, borderRadius: "50%", background: s.color, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Social id={s.id} size={14} /></span>
              <span className="nm">{s.name} <span className="dim mono" style={{ fontSize: 11 }}>{s.domains.length} domains</span></span>
              <div className="edit-row-tools">
                <button className="iconbtn" onClick={() => setModal({ kind: "social", data: { mode: "edit", social: { ...s, domains: [...s.domains] } } })}><Icon name="edit" size={15} /></button>
                <button className="iconbtn danger" onClick={() => update(d => d.socials = d.socials.filter(x => x.id !== s.id))}><Icon name="trash" size={15} /></button>
              </div>
            </>
          )} />
          <button className="btn ghost sm" style={{ marginTop: 10 }} onClick={() => setModal({ kind: "social", data: { mode: "add", social: { id: uid("soc"), name: "", link: "", color: "#211e1a", domains: [] } } })}><Icon name="plus" size={15} /> Add social network</button>
        </EditSection>

        <EditSection num={4} title="Sections">
          <p className="dim" style={{ fontSize: 13, marginTop: -4, marginBottom: 10 }}>Every section of the site. Names (EN &amp; FR) and logo are set when you create a section — edit with <Icon name="edit" size={12} style={{ verticalAlign: "-1px" }} />. Toggle the menu, or open <Icon name="arrow" size={12} style={{ verticalAlign: "-1px" }} /> to manage its content.</p>
          <DragList items={db.sections} onReorder={n => update(d => d.sections = n)} renderRow={(s) => (
            <>
              <span className="sec-row-logo" style={{ background: s.logo ? "#fff" : "var(--accent)", padding: s.logo ? 0 : undefined }}>
                {s.logo ? <img src={s.logo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <Icon name={s.kind === "video" ? "play" : s.kind === "podcast" ? "msg" : "edit"} size={14} />}
              </span>
              <span className="nm">{s.label} <span className="dim mono" style={{ fontSize: 11, fontWeight: 400 }}>{s.route}</span></span>
              <div className="edit-row-tools">
                <button className={"toggle" + (s.inMenu ? " on" : "")} title={s.inMenu ? "Visible publicly — hide" : "Hidden — show publicly"} onClick={() => update(z => { const x = z.sections.find(q => q.id === s.id); if (x) x.inMenu = !s.inMenu; })} />
                <button className="iconbtn" title="edit section" onClick={() => setModal({ kind: "section", data: { mode: "edit", section: { ...s } } })}><Icon name="edit" size={15} /></button>
                <button className="iconbtn" title="manage content" onClick={() => go(s.route)}><Icon name="arrow" size={15} /></button>
              </div>
            </>
          )} />
          {/* the "Other" pseudo-section */}
          <div className="draglist" style={{ marginTop: 8 }}>
            <div className="dragrow" style={{ cursor: "default", borderStyle: "dashed" }}>
              <span className="logo" style={{ width: 26, height: 26, borderRadius: 8, background: "var(--c-violet)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="compass" size={14} /></span>
              <span className="nm">Other <span className="dim mono" style={{ fontSize: 11 }}>{(db.otherPages || []).length} pages · not in menu</span></span>
              <div className="edit-row-tools">
                <button className="iconbtn" title="manage other pages" onClick={() => setModal({ kind: "other" })}><Icon name="arrow" size={15} /></button>
              </div>
            </div>
          </div>
          <button className="btn ghost sm" style={{ marginTop: 10 }} onClick={() => setModal({ kind: "section", data: { mode: "add", section: { label: "", kind: "blog", type: "multimodal", route: "", logo: null, inMenu: true, tr: {} } } })}><Icon name="plus" size={15} /> Add section</button>
        </EditSection>
      </>
    );
  }

  return (
    <>
      {body}
      {modal && modal.kind === "social" && <SocialModal data={modal.data} domains={db.domains} onClose={close}
        onSave={(s) => { update(d => { const i = d.socials.findIndex(x => x.id === s.id); if (i >= 0) d.socials[i] = s; else d.socials.push(s); }); close(); }}
        onDelete={(id) => update(d => d.socials = d.socials.filter(x => x.id !== id))} />}
      {modal && modal.kind === "app" && <AppModal data={modal.data} onClose={close}
        onSave={(a) => { update(d => { if (modal.data.mode === "add") d.apps.push({ ...a, id: uid("app") }); else { const i = d.apps.findIndex(x => x.id === a.id); d.apps[i] = a; } }); close(); }}
        onDelete={(id) => update(d => d.apps = d.apps.filter(x => x.id !== id))} />}
      {modal && modal.kind === "addDomain" && <NameModal title="Add domain" label="Domain name" onClose={close} onSave={addDomain} />}
      {modal && modal.kind === "section" && <SectionModal data={modal.data} onClose={close} onSave={saveSection} onDelete={(id) => update(d => d.sections = d.sections.filter(x => x.id !== id))} />}
      {modal && modal.kind === "other" && <OtherPagesModal pages={db.otherPages || []} onClose={close} onChange={(list) => update(d => d.otherPages = list)} />}
    </>
  );
}

/* small inline language switch shown atop translatable panels */
function LangNote({ required }) {
  const { lang, setLang } = useNav();
  return (
    <div className="lang-edit-bar" style={{ marginBottom: 14 }}>
      <span className="leb-k">Editing in</span>
      <div className="leb-tabs">
        <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
        <button className={lang === "fr" ? "on" : ""} onClick={() => setLang("fr")}>FR</button>
      </div>
      <span className="grow" />
      {required && <span className="dim mono" style={{ fontSize: 11 }}>both languages required</span>}
    </div>
  );
}

/* =================== DOMAIN panels =================== */
function DomainEditPanel({ domain, activeWin }) {
  const { db, update } = useStore();
  const { lang } = useNav();
  const [featQuery, setFeatQuery] = uSe("");
  const [presPicker, setPresPicker] = uSe(false);
  const dm = db.domains.find(d => d.id === domain.id) || domain;
  const patch = (fn) => update(d => { const x = d.domains.find(z => z.id === domain.id); fn(x); });
  const dlf = domLangFields(dm, lang);
  const setDL = (key, value) => update(d => {
    const x = d.domains.find(z => z.id === domain.id); if (!x) return;
    if (lang === "fr") { x.tr = x.tr || {}; x.tr.fr = x.tr.fr || {}; x.tr.fr[key] = value; }
    else x[key] = value;
  });

  if (activeWin === 3) return <EmptyPanel msg="Window 3 is shared across all domains — edit its Apps & Navigation from the home page in edit mode." />;

  if (activeWin === 2) {
    const langFull = lang === "fr" ? "French" : "English";
    const featList = (dm.featured && dm.featured[lang]) || [];
    const domContent = db.content.filter(c => c.published !== false && langExists(c, lang) && domainsOf(c).includes(domain.id));
    const ranked = [...domContent].sort((a, b) => (b.rating || 0) - (a.rating || 0));
    const q = (featQuery || "").trim().toLowerCase();
    const shown = q ? ranked.filter(c => (wholeLang(c, lang).title || "").toLowerCase().includes(q)) : ranked;
    const toggleFeat = (id) => patch(x => {
      x.featured = (x.featured && typeof x.featured === "object" && !Array.isArray(x.featured)) ? x.featured : { en: [], fr: [] };
      const f = x.featured[lang] || [];
      x.featured[lang] = f.includes(id) ? f.filter(i => i !== id) : (f.length >= 4 ? f : [...f, id]);
    });
    return (
      <>
        <EditSection num={1} title="About — quote">
          <textarea rows={2} value={dlf.quote} onChange={e => setDL("quote", e.target.value)} />
        </EditSection>
        <EditSection num={2} title={"Top picks · " + (lang === "fr" ? "FR" : "EN") + " (max 4)"}>
          <p className="dim" style={{ fontSize: 13, marginTop: -4, marginBottom: 10 }}>Picks are <b>separate per language</b> — you are choosing the <b>{langFull}</b> selection now. Only pieces <b>published and actually written in {langFull}</b> are listed. Leave empty to auto-show the <b>4 best-rated {langFull}</b> pieces.</p>
          <div style={{ position: "relative", marginBottom: 10 }}>
            <span style={{ position: "absolute", left: 11, top: 9, color: "var(--muted)" }}><Icon name="search" size={16} /></span>
            <input value={featQuery} onChange={e => setFeatQuery(e.target.value)} placeholder="Search an article by name…" style={{ paddingLeft: 34 }} />
          </div>
          {shown.length === 0
            ? <span className="dim mono" style={{ fontSize: 12 }}>{domContent.length === 0 ? "No " + langFull + " content for this domain yet." : "No match."}</span>
            : <MultiSelect options={shown.map(c => { const tt = wholeLang(c, lang).title || c.ref; return ({ id: c.id, label: tt.length > 30 ? tt.slice(0, 28) + "…" : tt }); })} selected={featList} onToggle={toggleFeat} />}
        </EditSection>
        <EditSection num={3} title="Presentation block">
          <label>Media <span className="dim mono" style={{ fontWeight: 400, fontSize: 11 }}>shared across languages — load from the media library (by media type / media key) or upload</span></label>
          <ImageUpload value={dm.presImage} onChange={v => patch(x => { x.presImage = v; x.presImageKey = ""; })} label="upload portrait / photo / short video poster" aspect="16/9" />
          <div className="row gap-8 wrap" style={{ marginTop: 8, alignItems: "center" }}>
            <button type="button" className="chip" onClick={() => setPresPicker(true)}><Icon name="compass" size={12} style={{ verticalAlign: "-2px", marginRight: 3 }} />From media library</button>
            {dm.presImageKey && <span className="asset-ref"><span className="ar-ic"><Icon name="compass" size={14} /></span><span className="ar-body"><span className="ar-key mono">{dm.presImageKey}</span></span><button className="iconbtn sm danger" onClick={() => patch(x => { x.presImage = null; x.presImageKey = ""; })}><Icon name="close" size={13} /></button></span>}
          </div>
          <div style={{ marginTop: 12 }}><label>Title (after name)</label><input value={dlf.presTitle} onChange={e => setDL("presTitle", e.target.value)} /></div>
          <div style={{ marginTop: 10 }}>
            <label>Body</label>
            <textarea rows={5} value={dlf.presBody} onChange={e => setDL("presBody", e.target.value)} />
            <div className="dim mono" style={{ fontSize: 11, marginTop: 5 }}>Formatting: <b>**bold**</b> · <span style={{ color: "var(--accent-ink)" }}>[link text](https://…)</span></div>
          </div>
        </EditSection>
        {presPicker && window.MediaPicker && <window.MediaPicker type="image" title="Presentation media" onPick={(id) => { const m = window.assetById(db, id); patch(x => { x.presImage = (m && window.assetSrc(m)) || x.presImage; x.presImageKey = m ? m.key : ""; }); }} onClose={() => setPresPicker(false)} />}
      </>
    );
  }
  const allSocials = db.socials;
  const toggleSocial = (id) => patch(x => { x.socials = (x.socials || []).includes(id) ? x.socials.filter(i => i !== id) : [...(x.socials || []), id]; });
  const toggleSection = (id) => patch(x => { x.sections = (x.sections || []).includes(id) ? x.sections.filter(i => i !== id) : [...(x.sections || []), id]; });
  const toggleExtra = (id) => patch(x => { x.extraPages = (x.extraPages || []).includes(id) ? x.extraPages.filter(i => i !== id) : [...(x.extraPages || []), id]; });
  const otherOpts = (db.otherPages || []).filter(p => p.kind !== "secret");
  return (
    <>
      <EditSection num={1} title="Domain">
        <div className="field-row">
          <div><label>Route <span className="dim mono" style={{ fontWeight: 400, fontSize: 11 }}>shared</span></label><input value={dm.route} onChange={e => patch(x => { x.route = e.target.value; })} /></div>
          <div><label>Title (in hero)</label><input value={dlf.title} onChange={e => setDL("title", e.target.value)} /></div>
        </div>
        <div className="field-row" style={{ marginTop: 10, alignItems: "flex-end" }}>
          <div><label>Center illustration</label><div className="ph" style={{ height: 40, fontSize: 11 }}>{dm.appEmbed ? "app page (embedded)" : `pattern: ${dm.art}`}<span className="ph-tag">{dm.appEmbed ? "app" : "svg"}</span></div></div>
          <div style={{ flex: ".4" }}><label>Display</label><button className={"toggle" + (dm.display ? " on" : "")} onClick={() => patch(x => x.display = !x.display)} /></div>
        </div>
        <div style={{ marginTop: 10 }}>
          <label>Illustration source <span className="dim mono" style={{ fontWeight: 400, fontSize: 11 }}>load an SVG / app page by URL (route or id) — leave empty for the generated pattern</span></label>
          <input value={dm.appEmbed || ""} onChange={e => patch(x => x.appEmbed = e.target.value || null)} placeholder="/other/my-app   or   https://…" />
        </div>
        <div style={{ marginTop: 12 }}><label>Sections shown on the illustration</label>
          <MultiSelect options={db.sections.map(s => ({ id: s.id, label: s.label }))} selected={dm.sections || []} onToggle={toggleSection} />
        </div>
        <div style={{ marginTop: 12 }}><label>Other → extra pages (CV, etc.) shown as links</label>
          <MultiSelect options={otherOpts.map(p => ({ id: p.id, label: p.label }))} selected={dm.extraPages || []} onToggle={toggleExtra} />
        </div>
      </EditSection>
      <EditSection num={2} title="Social networks (this domain)">
        <p className="dim" style={{ fontSize: 13, marginTop: -4, marginBottom: 10 }}>Pick from those defined on the home page. Drag to reorder.</p>
        <MultiSelect options={allSocials.map(s => ({ id: s.id, label: s.name }))} selected={dm.socials || []} onToggle={toggleSocial} />
        {(dm.socials || []).length > 0 && (
          <div style={{ marginTop: 12 }}>
            <DragList items={(dm.socials || []).map(id => ({ id, ...allSocials.find(s => s.id === id) }))} onReorder={n => patch(x => x.socials = n.map(s => s.id))} renderRow={(s) => (
              <><span className="logo" style={{ width: 24, height: 24, borderRadius: "50%", background: s.color, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Social id={s.id} size={13} /></span><span className="nm">{s.name}</span></>
            )} />
          </div>
        )}
      </EditSection>
    </>
  );
}

function EmptyPanel({ msg }) {
  return <div className="edit-section" style={{ textAlign: "center", color: "var(--muted)" }}><Icon name="check" size={22} /><p style={{ margin: "8px 0 0" }}>{msg}</p></div>;
}

/* =================== GLOBAL (site-wide) settings =================== */
/* Reached from the Admin button → "Open settings panel". Mirrors the
   domain panel: Window 1 / 2 / 3 tabs, same fixed height, centered. */
function GlobalSettingsPanel() {
  const [win, setWin] = uSe(1);
  return (
    <>
      <div className="ep2-tabs">
        <div className="row gap-8" style={{ flexWrap: "wrap" }}>
          {[1, 2, 3].map(n => (
            <button key={n} className={"chip" + (win === n ? " on" : "")} onClick={() => setWin(n)}>
              Window {n} — {["Hero", "About", "Footer"][n - 1]}
            </button>
          ))}
        </div>
      </div>
      <div className={"ep2-cols" + (win === 1 ? " gs-win1" : "")}>
        <HomeEditPanel activeWin={win} />
      </div>
    </>
  );
}

/* =================== BANNER =================== */
function EditBanner({ domain, isHome, activeWin, goWindow }) {
  const { go, setEdit } = useNav();
  const { db } = useStore();
  const [open, setOpen] = uSe(true);
  const [saved, setSaved] = uSe(false);
  const winLabel = ["", "Window 1 — Hero", "Window 2 — About", "Window 3 — Footer"][activeWin] || "";

  const doSave = () => { setSaved(true); setTimeout(() => setSaved(false), 1800); };

  return (
    <div className="edit-banner">
      <div className="eb-head">
        <button className="eb-toggle" onClick={() => setOpen(v => !v)} title={open ? "Close panel" : "Open panel"}>
          <Icon name={open ? "left" : "right"} size={16} /> {open ? "Close" : "Open"} panel
        </button>
        <span className="warn-ico">!</span>
        <span className="eb-title">EDIT MODE {isHome ? "— Home" : "— " + domain.label}</span>
        <span className="dim mono eb-win" style={{ fontWeight: 400, color: "#5a3a06", fontSize: 12 }}>{winLabel}</span>
        <span className="grow" />
        {!isHome && <button className="btn sm" style={{ background: "#fff7ea" }} onClick={() => go("/")}><Icon name="home" size={15} /> Home</button>}
        <button className="btn sm" style={{ background: "#fff7ea" }} onClick={() => go("/board")}><Icon name="chart" size={15} /> Board</button>
        <button className="btn sm" style={{ background: "#fff" }} onClick={() => { setEdit(false); }}><Icon name="close" size={15} /> Exit edit</button>
      </div>
      {open && (
        <div className="edit-panel">
          <div className="edit-panel-inner">
            <div className="row gap-8" style={{ marginBottom: 14 }}>
              {[1, 2, 3].map(n => (
                <button key={n} className={"chip" + (activeWin === n ? " on" : "")} onClick={() => goWindow(n)}>Window {n}</button>
              ))}
            </div>
            {isHome ? <HomeEditPanel activeWin={activeWin} /> : <DomainEditPanel domain={domain} activeWin={activeWin} />}
            <div className="row" style={{ justifyContent: "flex-end", marginTop: 8, gap: 10 }}>
              {saved && <span className="row gap-8" style={{ color: "var(--c-green)", fontWeight: 700, fontFamily: "var(--font-display)" }}><Icon name="check" size={18} /> Saved</span>}
              <button className="btn accent" onClick={doSave}><Icon name="save" size={16} /> Save changes</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { EditBanner, HomeEditPanel, DomainEditPanel, GlobalSettingsPanel, NameModal, MultiSelect, ToggleRow, EditSection, SocialModal, AppModal, EmptyPanel });
