/* ============================================================
   Global chrome — persistent Edit-Mode banner (shown on EVERY
   page while authenticated + editing), a centered drop-down
   settings panel, and the content-linked Feedback overlay.
   ============================================================ */
const { useState: uSx, useEffect: uEx, createContext: createCtxX, useContext: useCtxX, useCallback: useCbX } = React;

/* ---- Edit-chrome context: panel open state + domain-page registration ---- */
const EditCtx = createCtxX(null);
function useEdit() { return useCtxX(EditCtx) || {}; }

function EditChromeProvider({ children }) {
  const [panelOpen, setPanelOpen] = uSx(false);
  const [panelMode, setPanelMode] = uSx("page");   // 'page' (current domain) | 'global' (site-wide)
  const [reg, setRegState] = uSx(null);   // { domain, isHome, activeWin, goWindow }
  const setReg = useCbX((v) => setRegState(v), []);
  const value = { panelOpen, setPanelOpen, panelMode, setPanelMode, reg, setReg };
  return <EditCtx.Provider value={value}>{children}</EditCtx.Provider>;
}

/* ---- Feedback context: open a content-linked feedback popup anywhere ---- */
const FeedbackCtx = createCtxX(null);
function useFeedback() { return useCtxX(FeedbackCtx) || { open: () => {} }; }

function FeedbackProvider({ children }) {
  const [subject, setSubject] = uSx(null); // null | { kind, ref, title } | { kind:'general' }
  const open = useCbX((subj) => setSubject(subj || { kind: "general" }), []);
  const close = useCbX(() => setSubject(null), []);
  return (
    <FeedbackCtx.Provider value={{ open, close, subject }}>
      {children}
      {subject && <FeedbackOverlay subject={subject} onClose={close} />}
    </FeedbackCtx.Provider>
  );
}

/* ===================== FEEDBACK OVERLAY (transparent popup) ===================== */
function FeedbackOverlay({ subject, onClose }) {
  const { db, update } = useStore();
  const { lang } = useNav();
  const fr = lang === "fr";
  const [f, setF] = uSx({ name: "", rating: 0, message: "" });
  const [sent, setSent] = uSx(false);
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));
  const linked = subject && subject.kind !== "general";
  const valid = f.message.trim();
  // relative path crumb — "On Blog/<title>"
  const secOf = (kind) => (db.sections || []).find(s => s.kind === kind);
  const crumb = linked ? `${(secOf(subject.kind) || {}).label || (subject.kind === "video" ? "Videos" : "Blog")}/${subject.title}` : "";
  uEx(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);
  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    update(d => {
      d.feedbacks.unshift({
        id: uid("f"), name: f.name.trim() || "Anon",
        date: new Date().toISOString().slice(0, 10), rating: f.rating || null,
        text: f.message,
        about: linked ? `${subject.kind === "video" ? "Video" : "Article"} · ${subject.title}` : null,
      });
      d.notifications.unshift({ id: uid("n"), tile: "t3", time: new Date().toISOString().slice(0, 16).replace("T", " "), text: linked ? `Feedback on “${subject.title}”.` : `New feedback received.` });
    });
    setSent(true);
  };
  return ReactDOM.createPortal(
    <div className="fb-scrim" onClick={onClose}>
      <div className="fb-pop" onClick={e => e.stopPropagation()}>
        <button className="iconbtn fb-close" onClick={onClose}><Icon name="close" size={18} /></button>
        {sent ? (
          <div className="center col gap-8" style={{ textAlign: "center", padding: "14px 6px" }}>
            <span className="iconbtn" style={{ width: 54, height: 54, borderRadius: "50%", background: "var(--accent)", color: "#fff", border: "none" }}><Icon name="check" size={28} /></span>
            <h3 style={{ fontSize: 24 }}>{fr ? "Merci !" : "Thank you!"}</h3>
            <p className="dim" style={{ maxWidth: 320 }}>{linked ? (fr ? "Votre note sur ce contenu vient d'arriver sur le tableau de bord." : "Your note on this piece just landed on the board.") : (fr ? "Votre feedback vient d'arriver sur le tableau de bord." : "Your feedback just landed on the board.")}</p>
            <button className="btn" onClick={onClose} style={{ marginTop: 4 }}>{fr ? "Fermer" : "Close"}</button>
          </div>
        ) : (
          <form className="col gap-14" onSubmit={submit}>
            <div className="mono" style={{ color: "var(--accent)", letterSpacing: ".14em", fontSize: 12 }}>{linked ? (fr ? "FEEDBACK SUR CE CONTENU" : "FEEDBACK ON THIS PIECE") : (fr ? "DONNER UN FEEDBACK" : "GIVE FEEDBACK")}</div>
            <h3 style={{ fontSize: "clamp(22px,3vw,28px)", lineHeight: 1.08, margin: 0 }}>{linked ? subject.title : (fr ? "Dites-moi ce que vous en pensez" : "Tell me what you think")}</h3>
            {linked && <div className="fb-subject"><Icon name={subject.kind === "video" ? "play" : "edit"} size={14} /><span>{fr ? "Sur" : "On"} <b className="mono">{crumb}</b></span></div>}
            <div>
              <label>{fr ? "Nom" : "Name"} <span className="dim mono" style={{ fontWeight: 400, fontSize: 11 }}>{fr ? "optionnel" : "optional"}</span></label>
              <input value={f.name} onChange={e => set("name", e.target.value)} placeholder={fr ? "Anonyme" : "Anonymous"} />
            </div>
            <div>
              <label>{fr ? "Note" : "Rating"} <span className="dim mono" style={{ fontWeight: 400, fontSize: 11 }}>{fr ? "optionnel" : "optional"}</span></label>
              <div className="row gap-8" style={{ color: "var(--c-amber)" }} onMouseLeave={() => {}}>
                {[1, 2, 3, 4, 5].map(i => (
                  <button type="button" key={i} className="ratestar" onClick={() => set("rating", i === f.rating ? 0 : i)}><Icon name={i <= f.rating ? "starF" : "star"} size={26} /></button>
                ))}
              </div>
            </div>
            <div><label>{fr ? "Message" : "Message"} *</label><textarea rows={4} value={f.message} onChange={e => set("message", e.target.value)} placeholder={fr ? "Ce qui marche, ce qui cloche, ce que vous aimeriez voir\u2026" : "What worked, what didn't, what you'd love to see\u2026"} autoFocus /></div>
            <div className="row gap-8" style={{ justifyContent: "flex-end" }}>
              <button type="button" className="btn ghost" onClick={onClose}>{fr ? "Annuler" : "Cancel"}</button>
              <button className="btn accent" type="submit" disabled={!valid} style={{ opacity: valid ? 1 : .5 }}><Icon name="arrow" size={16} /> {fr ? "Envoyer" : "Send"}</button>
            </div>
          </form>
        )}
      </div>
    </div>,
    document.body
  );
}

/* ===================== PERSISTENT MODE BANNER (all pages) ===================== */
function GlobalEditBanner() {
  const { db } = useStore();
  const { go, setEdit, setReview, setPublish, setTmode, route, role, isAdmin, reviewMode, publishMode, testerMode, lang } = useNav();
  const { panelOpen, setPanelOpen, panelMode, setPanelMode, reg } = useEdit();
  const [saved, setSaved] = uSx(false);
  const p = db.profile;
  const fr = lang === "fr";
  const isReview = !!reviewMode;
  const isPublish = !!publishMode;
  const isTester = !!testerMode;
  const showPanel = isAdmin;   // only the admin gets the site-settings panel

  // editing context label for non-domain pages
  const path = route.path;
  let ctxLabel;
  if (reg) ctxLabel = reg.domain.label;
  else if (path.startsWith("/blog") || path.startsWith("/videos") || path.startsWith("/podcasts")) ctxLabel = fr ? "Section" : "Section";
  else if (path === "/about") ctxLabel = "About me";
  else if (path.startsWith("/legal")) ctxLabel = fr ? "Page légale" : "Legal page";
  else if (path.startsWith("/other")) ctxLabel = fr ? "Page Other" : "Other page";
  else if (path === "/" || path === "") ctxLabel = fr ? "Accueil" : "Workspace";
  else ctxLabel = "Page";

  const openPagePanel = () => {
    if (panelOpen && panelMode === "page") { setPanelOpen(false); return; }
    setPanelMode("page"); setPanelOpen(true);
  };
  const openGlobalPanel = () => {
    if (panelOpen && panelMode === "global") { setPanelOpen(false); return; }
    setPanelMode("global"); setPanelOpen(true);
  };
  const toBoard = () => { setEdit(false); go("/board"); };
  const exitMode = () => { if (isReview) setReview(false); else if (isPublish) setPublish(false); else if (isTester) setTmode(false); else setEdit(false); go(p.defaultRoute); };
  const doSave = () => { setSaved(true); setTimeout(() => setSaved(false), 1600); };

  const pageOpen = panelOpen && panelMode === "page";
  const globalOpen = panelOpen && panelMode === "global";
  const panelTitle = panelMode === "global" ? (fr ? "Réglages du site — global" : "Site settings — global") : `${fr ? "Édition" : "Editing"} — ${ctxLabel}`;
  const modeLabel = isReview ? (fr ? "MODE RELECTURE" : "REVIEWER MODE")
    : isPublish ? (fr ? "MODE PUBLICATION" : "PUBLISHER MODE")
    : isTester ? (fr ? "MODE TESTEUR" : "TESTER MODE")
    : (fr ? "MODE ÉDITION" : "EDIT MODE");
  const exitLabel = isReview ? (fr ? "Fermer le mode relecture" : "Close review mode")
    : isPublish ? (fr ? "Fermer le mode publication" : "Close publisher mode")
    : isTester ? (fr ? "Fermer le mode testeur" : "Close tester mode")
    : (fr ? "Fermer le mode édition" : "Close edit mode");
  const bannerCls = isReview ? " is-review" : isPublish ? " is-publish" : isTester ? " is-tester" : "";

  return (
    <div className={"edit-banner" + bannerCls}>
      <div className="eb-head">
        {/* LEFT — admin only: open the current page's settings panel */}
        {showPanel && (
          <button className="eb-btn primary" onClick={openPagePanel}>
            <Icon name={pageOpen ? "up" : "down"} size={15} /> {pageOpen ? (fr ? "Fermer" : "Close") : (fr ? "Ouvrir" : "Open")} {fr ? "le panneau" : "panel"}
          </button>
        )}
        <span className="warn-ico">!</span>
        <span className="eb-mode">{modeLabel}</span>
        {window.RoleBadge && <span className="eb-role"><window.RoleBadge role={role} /></span>}
        <span className="eb-ctx domain"><Icon name="globe" size={13} /> {ctxLabel.toUpperCase()}</span>

        <span className="grow" />

        {/* RIGHT — site settings + quick board link (admin) + exit. Identity lives in the page header. */}
        {showPanel && <button className={"eb-btn" + (globalOpen ? " primary" : "")} onClick={openGlobalPanel}><Icon name="globe" size={15} /> {fr ? "Réglages du site" : "Site settings"}</button>}
        {isAdmin && <button className="eb-btn" onClick={toBoard}><Icon name="chart" size={15} /> {fr ? "Tableau de bord" : "Board"}</button>}
        <button className="eb-btn exit" onClick={exitMode}><Icon name="close" size={15} /> {exitLabel}</button>
      </div>

      {showPanel && panelOpen && (
        <>
          <div className="ep-scrim" onClick={() => setPanelOpen(false)} />
          <div className="edit-panel-v2">
            <div className="ep2-head">
              <div className="row gap-8" style={{ alignItems: "center" }}>
                <span className="ep2-kicker">{panelMode === "global" ? "SITE" : "PAGE"} SETTINGS</span>
                <h3 className="ep2-title">{panelTitle}</h3>
              </div>
              <button className="iconbtn" onClick={() => setPanelOpen(false)}><Icon name="close" size={18} /></button>
            </div>

            <div className="ep2-body">
              {panelMode === "global"
                ? (window.GlobalSettingsPanel ? <window.GlobalSettingsPanel /> : null)
                : (reg ? <DomainPanelRouter reg={reg} /> : <NonDomainPanel ctxLabel={ctxLabel} />)}
            </div>

            <div className="ep2-foot">
              {saved && <span className="row gap-8" style={{ color: "var(--c-green)", fontWeight: 700, fontFamily: "var(--font-display)" }}><Icon name="check" size={18} /> Saved</span>}
              <span className="dim mono" style={{ fontSize: 11 }}>Changes apply live</span>
              <button className="btn accent" onClick={doSave}><Icon name="save" size={16} /> Save changes</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

/* window tabs + the right per-window editor for a domain/home page */
function DomainPanelRouter({ reg }) {
  const { domain, activeWin, goWindow, isHome } = reg;
  const { lang, setLang } = useNav();
  return (
    <>
      <div className="ep2-tabs">
        <div className="row gap-8" style={{ flexWrap: "wrap" }}>
          {[1, 2, 3].map(n => (
            <button key={n} className={"chip" + (activeWin === n ? " on" : "")} onClick={() => goWindow(n)}>
              Window {n} — {["Hero", "About", "Footer"][n - 1]}
            </button>
          ))}
        </div>
        {activeWin === 2 && !isHome && (
          <div className="lang-inline">
            <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>
          </div>
        )}
      </div>
      <div className={"ep2-cols" + (activeWin === 2 && !isHome ? " win2-layout" : "")}>
        {isHome ? <HomeEditPanel activeWin={activeWin} /> : <DomainEditPanel domain={domain} activeWin={activeWin} />}
      </div>
    </>
  );
}

/* generic panel for section / article / legal / about pages */
function NonDomainPanel({ ctxLabel }) {
  const { setPanelMode } = useEdit();
  return (
    <div className="edit-section" style={{ maxWidth: 640 }}>
      <div className="es-title"><span className="es-num"><Icon name="edit" size={12} /></span>Editing this page</div>
      <p className="dim" style={{ fontSize: 14, marginTop: -4, lineHeight: 1.5 }}>
        You're editing a <b>{ctxLabel.toLowerCase()}</b> page. Its content is edited inline — use the
        <span className="mono"> Add</span>, <Icon name="edit" size={13} style={{ verticalAlign: "-2px" }} /> and
        <Icon name="trash" size={13} style={{ verticalAlign: "-2px" }} /> controls directly on the page. Site-wide structure
        (domains, sections, socials, apps, navigation) lives under <b>Admin → Open settings panel</b>.
      </p>
      <div className="row gap-8" style={{ marginTop: 12, flexWrap: "wrap" }}>
        <button className="btn ghost sm" onClick={() => setPanelMode("global")}><Icon name="globe" size={14} /> Open site settings</button>
      </div>
    </div>
  );
}

Object.assign(window, { EditChromeProvider, useEdit, FeedbackProvider, useFeedback, GlobalEditBanner, FeedbackOverlay });
