/* ============================================================
   WCW Product Hub — Root app: role switching + routing + shell
   ============================================================ */
const { useState: useStateApp, useEffect: useEffectApp, useRef: useRefApp } = React;

let TOAST_ID = 0;

const ACCENTS = {
  "WCW Red":  { red: "0.515 0.165 26",  bright: "0.575 0.205 27", ink: "0.44 0.15 27",  soft: "0.955 0.028 26",  line: "0.88 0.06 26" },
  "Forest":   { red: "0.5 0.11 150",    bright: "0.56 0.13 150",  ink: "0.42 0.10 150", soft: "0.955 0.03 150",  line: "0.86 0.06 150" },
  "Indigo":   { red: "0.5 0.15 268",    bright: "0.57 0.18 268",  ink: "0.43 0.14 268", soft: "0.955 0.03 268",  line: "0.87 0.05 268" },
  "Charcoal": { red: "0.34 0.02 60",    bright: "0.42 0.025 60",  ink: "0.30 0.02 60",  soft: "0.95 0.005 60",   line: "0.85 0.008 60" },
};
function accentVars(name) {
  const a = ACCENTS[name] || ACCENTS["WCW Red"];
  return {
    "--red": `oklch(${a.red})`, "--red-bright": `oklch(${a.bright})`,
    "--red-ink": `oklch(${a.ink})`, "--red-soft": `oklch(${a.soft})`, "--red-line": `oklch(${a.line})`,
  };
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "WCW Red",
  "homeLayout": "split",
  "guidance": "ontap",
  "density": "regular"
}/*EDITMODE-END*/;

function RoleSwitcher({ me, onPick }) {
  const [open, setOpen] = useStateApp(false);
  const ref = useClickOutside(() => setOpen(false));
  const D = window.HUB_DATA;
  return (
    <div style={{ position: "relative" }} ref={ref}>
      <button className="role-switch" onClick={() => setOpen(o => !o)}>
        <Avatar name={me.name} init={me.init} color={me.color} />
        <div className="who"><b>{me.name}</b><span>{me.role}</span></div>
        <Icon name="chevDown" size={15} className="chev" />
      </button>
      {open && (
        <div className="menu" style={{ right: 0, top: "calc(100% + 8px)" }}>
          <div className="menu-label">View the hub as…</div>
          {D.ROLES.map(r => (
            <button key={r.id} className={`menu-item ${r.id === me.id ? "active" : ""}`} onClick={() => { onPick(r.id); setOpen(false); }}>
              <Avatar name={r.name} init={r.init} color={r.color} size="sm" />
              <div className="who"><b>{r.name}</b><span>{r.role} — {r.desc}</span></div>
              {r.id === me.id && <Icon name="check" size={15} className="tick" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function NotifPanel() {
  const [open, setOpen] = useStateApp(false);
  const ref = useClickOutside(() => setOpen(false));
  const items = [
    { who: "Marcus Reed", text: "mentioned you on TONIC WATER MEDITERRANEAN", time: "3d", role: "sales" },
    { who: "Joe Cretella", text: "flagged dimensions on SALMON ATLANTIC FRESH", time: "5d", role: "warehouse" },
    { who: "Yessenia Vega", text: "needs a GTIN for SHRIMP 16/20 EZ PEEL", time: "1d", role: "newitem" },
  ];
  return (
    <div style={{ position: "relative" }} ref={ref}>
      <button className="icon-btn" onClick={() => setOpen(o => !o)}><Icon name="bell" size={18} /><span className="dot"></span></button>
      {open && (
        <div className="menu" style={{ right: 0, top: "calc(100% + 8px)", minWidth: 320 }}>
          <div className="menu-label">Notifications</div>
          {items.map((n, i) => (
            <div key={i} className="menu-item" style={{ alignItems: "flex-start" }}>
              <Avatar name={n.who} size="sm" />
              <div className="who" style={{ whiteSpace: "normal" }}><b>{n.who}</b> <span style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{n.text}</span><div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>{n.time} ago</div></div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Rail({ view, role, products, onNav, me }) {
  const D = window.HUB_DATA;
  const stalled = products.filter(p => p.days >= 7).length;
  const myQueue = {
    purchaser: products.filter(p => p.stage === "intake").length,
    marketing: products.filter(p => p.stage === "mkt").length,
    newitem: products.filter(p => p.stage === "setup").length,
    sales: products.filter(p => p.accounts && p.accounts.length).length,
    warehouse: products.filter(p => p.stage === "setup").length,
    leadership: stalled,
    vendor: products.filter(p => /fever/i.test(p.vendor)).length,
  }[role] || 0;

  const nav = [
    { id: "home", label: "Home", icon: "home" },
    { id: "board", label: "Pipeline board", icon: "board" },
    { id: "list", label: "All products", icon: "list", count: products.length },
  ];
  return (
    <nav className="rail">
      <div className="rail-section">
        {nav.map(n => (
          <button key={n.id} className={`nav-item ${view === n.id ? "active" : ""}`} onClick={() => onNav(n.id)}>
            <span className="nav-ico"><Icon name={n.icon} size={17} /></span>{n.label}
            {n.count != null && <span className="count">{n.count}</span>}
          </button>
        ))}
      </div>

      <div className="rail-section">
        <div className="rail-head">Your work</div>
        <button className={`nav-item`} onClick={() => onNav("queue")}>
          <span className="nav-ico"><Icon name="inbox" size={17} /></span>My queue
          {myQueue > 0 && <span className="count">{myQueue}</span>}
        </button>
        <button className="nav-item" onClick={() => onNav("stalled")}>
          <span className="nav-ico"><Icon name="clock" size={17} /></span>Stalled
          {stalled > 0 && <span className="count alert">{stalled}</span>}
        </button>
      </div>

      {(role === "purchaser" || role === "newitem") && (
        <div className="rail-section">
          {role === "purchaser" && (
            <button className="nav-item" style={{ background: "var(--red)", color: "#fff", marginBottom: 8 }} onClick={() => onNav("intake")}>
              <span className="nav-ico" style={{ color: "#fff" }}><Icon name="plus" size={17} /></span>New product
            </button>
          )}
          <button className="nav-item" onClick={() => onNav("reactivate")}>
            <span className="nav-ico"><Icon name="box" size={17} /></span>Reactivate product
            <span className="count">{D.DISCONTINUED.length}</span>
          </button>
        </div>
      )}

      <div className="rail-foot">
        <div className="help-card">
          <b style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 5 }}><Icon name="book" size={14} style={{ color: "var(--red)", flexShrink: 0 }} /> Field glossary</b>
          <p>Every PPRO field, what it means, and who fills it — no more guessing.</p>
        </div>
      </div>
    </nav>
  );
}

function App() {
  const D = window.HUB_DATA;
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [roleId, setRoleId] = useStateApp("purchaser");
  const [view, setView] = useStateApp("home");        // home | board | list | detail | intake | review | reactivate | reactivation
  const [selId, setSelId] = useStateApp(null);
  const [reactId, setReactId] = useStateApp(null);
  const [filter, setFilter] = useStateApp("all");
  const [listTitle, setListTitle] = useStateApp("All products");
  const [toasts, setToasts] = useStateApp([]);
  const [products, setProducts] = useStateApp(() => D.PRODUCTS.map(p => ({ ...p })));
  const mainRef = useRefApp(null);

  const me = D.roleById(roleId);
  const selected = products.find(p => p.id === selId);
  const reactItem = D.DISCONTINUED.find(p => p.id === reactId);

  const pushToast = (msg, icon) => {
    const id = ++TOAST_ID;
    setToasts(t => [...t, { id, msg, icon }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 2600);
  };
  const scrollTop = () => { if (mainRef.current) mainRef.current.scrollTop = 0; };

  const go = (v) => { setView(v); scrollTop(); };
  const openProduct = (p) => { setSelId(p.id); setView("detail"); scrollTop(); };

  // rail nav handler
  const onNav = (id) => {
    if (id === "home") go("home");
    else if (id === "board") { setFilter("all"); go("board"); }
    else if (id === "list") { setFilter("all"); setListTitle("All products"); go("list"); }
    else if (id === "intake") go("intake");
    else if (id === "reactivate") go("reactivate");
    else if (id === "queue") {
      const map = { purchaser: "intake", marketing: "mkt", newitem: "setup", warehouse: "setup" };
      setFilter(map[roleId] || "all"); setListTitle("My queue"); go("list");
    }
    else if (id === "stalled") { setFilter("stalled"); setListTitle("Stalled products"); go("list"); }
  };

  // flow strip click → board filtered to stage (or board if null)
  const onStage = (stageId) => {
    if (stageId) { setFilter("all"); setListTitle(D.STAGES.find(s => s.id === stageId).name + " stage"); }
    setFilter(stageId || "all");
    go("board");
  };

  // move product to a stage (board drag, or advance)
  const moveProduct = (id, stage) => {
    setProducts(ps => ps.map(p => {
      if (p.id !== id) return p;
      const idx = D.stageIndex(stage);
      const progress = [22, 60, 88, 100][idx] ?? p.progress;
      const owner = { intake: p.buyer, mkt: "Lauren Chen", setup: "Yessenia Vega", live: "Yessenia Vega" }[stage];
      const act = [...(p.activity || []), { who: me.name, action: `moved this to ${D.STAGES.find(s => s.id === stage).name}`, time: "just now" }];
      return { ...p, stage, progress, assignedTo: owner, days: 0, activity: act };
    }));
    const prod = products.find(p => p.id === id);
    pushToast(`${prod ? prod.name.split(" ").slice(0, 2).join(" ") : "Product"} → ${D.STAGES.find(s => s.id === stage).name}`, "arrowRight");
  };

  const addComment = (id, c) => {
    setProducts(ps => ps.map(p => p.id === id ? { ...p, comments: [...(p.comments || []), c], activity: [...(p.activity || []), { who: c.who, action: "added a comment", time: "just now" }] } : p));
    pushToast("Comment posted", "chat");
  };

  // intake submit → create a new product in marketing? Actually it's the tonic; advance to mkt
  const submitIntake = (vals, draft) => {
    // update the tonic product with drafted fields and move to marketing
    setProducts(ps => {
      const exists = ps.find(p => p.id === "tonic");
      const drafted = draft ? { pproDesc: draft.ppro_name, cls: draft.klass } : {};
      const upd = ps.map(p => p.id === "tonic"
        ? { ...p, ...drafted, stage: "mkt", progress: 60, assignedTo: "Lauren Chen", days: 0, flags: [], activity: [...(p.activity || []), { who: me.name, action: "submitted to Marketing", time: "just now" }] }
        : p);
      return upd;
    });
    pushToast("Submitted to Marketing", "check");
    setSelId("tonic"); setView("detail"); scrollTop();
  };

  // reactivation: pick a dormant item → review with flags → bring it back into the active pipeline
  const pickReactivation = (item) => { setReactId(item.id); go("reactivation"); };
  const confirmReactivation = (item, updates) => {
    const np = {
      ...item, ...updates,
      stage: "setup", progress: 88, days: 0, assignedTo: "Yessenia Vega",
      viaReactivation: true, isNew: false, flags: [],
      activity: [...(item.activity || []), { who: me.name, action: "reactivated this product — re-verified fields and sent to New Item Team", time: "just now" }],
    };
    setProducts(ps => ps.some(p => p.id === np.id) ? ps.map(p => p.id === np.id ? np : p) : [np, ...ps]);
    setReactId(null); setSelId(np.id); setView("detail"); scrollTop();
    pushToast(`${item.name.split(" ").slice(0, 2).join(" ")} reactivated → New Item Team`, "check");
  };

  const openReview = (p) => { setSelId(p.id); setView("review"); scrollTop(); };
  const approveReview = (id) => {
    moveProduct(id, "setup");
    pushToast("Approved & sent to New Item Team", "check");
    setView("detail"); scrollTop();
  };

  const exportCSV = () => pushToast("PPRO CSV exported (7 products)", "upload");

  return (
    <div className={`app ${t.density === "compact" ? "density-compact" : ""}`} style={accentVars(t.accent)}>
      {/* top bar */}
      <header className="topbar">
        <div className="brand">
          <div className="brand-mark"><img src="hub/wcw-mark.png" alt="WCW" /></div>
          <div className="brand-name"><b>Product Hub</b><span>What Chefs Want</span></div>
        </div>
        <div className="global-search">
          <Icon name="search" size={16} className="si" style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)" }} />
          <input placeholder="Search products, vendors, buyers…" onFocus={() => pushToast("Search is illustrative in this prototype", "search")} />
        </div>
        <div className="topbar-spacer"></div>
        <div className="topbar-actions">
          <button className="icon-btn" title="Field glossary" onClick={() => pushToast("Glossary opens the decoder reference", "book")}><Icon name="book" size={18} /></button>
          <NotifPanel />
          <div style={{ width: 1, height: 26, background: "var(--line-2)", margin: "0 6px" }}></div>
          <RoleSwitcher me={me} onPick={(id) => { setRoleId(id); setView("home"); scrollTop(); }} />
        </div>
      </header>

      <Rail view={view} role={roleId} products={products} onNav={onNav} me={me} />

      <main className="main" ref={mainRef}>
        {view === "home" && <HomeView products={products} role={roleId} me={me} onOpen={openProduct} onStage={onStage} onNew={() => go("intake")} onAdvance={moveProduct} onExport={exportCSV} layout={t.homeLayout} />}
        {view === "board" && <BoardView products={products} onOpen={openProduct} onMove={moveProduct} filter={filter} setFilter={setFilter} />}
        {view === "list" && <ListView products={products} onOpen={openProduct} filter={filter} setFilter={setFilter} title={listTitle} />}
        {view === "detail" && selected && <DetailView product={selected} me={me} role={roleId} onBack={() => go("board")} onComment={addComment} onAdvance={moveProduct} onReview={openReview} />}
        {view === "intake" && <IntakeView onBack={() => go("home")} onSubmit={submitIntake} pushToast={pushToast} alwaysGuide={t.guidance === "always"} />}
        {view === "review" && selected && <ReviewView product={selected} me={me} onBack={() => { setView("detail"); }} onApprove={approveReview} pushToast={pushToast} />}
        {view === "reactivate" && <ReactivatePicker onBack={() => go("home")} onPick={pickReactivation} />}
        {view === "reactivation" && reactItem && <ReactivationView item={reactItem} me={me} onBack={() => go("reactivate")} onReactivate={confirmReactivation} pushToast={pushToast} />}
      </main>

      <Toasts toasts={toasts} />

      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={{ "WCW Red": "#B9262C", "Forest": "#2E7D52", "Indigo": "#4659C9", "Charcoal": "#4A4540" }[t.accent]}
          options={["#B9262C", "#2E7D52", "#4659C9", "#4A4540"]}
          onChange={(hex) => {
            const map = { "#B9262C": "WCW Red", "#2E7D52": "Forest", "#4659C9": "Indigo", "#4A4540": "Charcoal" };
            setTweak("accent", map[hex] || "WCW Red");
          }} />
        <TweakSection label="Home layout" />
        <TweakRadio label="Hub home" value={t.homeLayout}
          options={["split", "stream"]}
          onChange={(v) => setTweak("homeLayout", v)} />
        <TweakSection label="Intake form" />
        <TweakRadio label="Field guidance" value={t.guidance}
          options={["ontap", "always"]}
          onChange={(v) => setTweak("guidance", v)} />
        <TweakSection label="Display" />
        <TweakRadio label="Density" value={t.density}
          options={["regular", "compact"]}
          onChange={(v) => setTweak("density", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
