/* ============================================================
   WCW Product Hub — Hub Home (role-tailored)
   ============================================================ */
const { useState: useStateHome } = React;

function FlowStrip({ products, onStage }) {
  const D = window.HUB_DATA;
  const counts = D.STAGES.map(s => ({
    ...s,
    n: products.filter(p => p.stage === s.id).length,
    stalled: products.filter(p => p.stage === s.id && p.days >= 7).length,
  }));
  return (
    <div className="flow">
      {counts.map((s, i) => (
        <div className="flow-stage" key={s.id} onClick={() => onStage(s.id)}>
          <div className="fs-top">
            <span className="fs-dot" style={{ background: `var(${s.varName})` }}></span>
            <span className="fs-name">{s.name}</span>
          </div>
          <div className="fs-count display tnum">{s.n}</div>
          <div className="fs-meta">
            {s.id === "intake" ? "in purchaser intake" :
             s.id === "mkt" ? "awaiting marketing" :
             s.id === "setup" ? "in PPRO setup" : "live this month"}
          </div>
          {s.stalled > 0 && <span className="tag warn fs-alert">{s.stalled} stalled</span>}
          {i < counts.length - 1 && <span className="flow-arrow"><Icon name="chevRight" size={18} /></span>}
        </div>
      ))}
    </div>
  );
}

function Task({ p, role, onOpen, onAdvance }) {
  const D = window.HUB_DATA;
  const S = D.STAGES.find(s => s.id === p.stage);
  const ask = {
    intake: <span><b>Complete intake</b> — {p.progress}% of your fields done</span>,
    mkt: <span><b>Review & approve</b> AI-drafted naming and copy</span>,
    setup: <span><b>Set up in PPRO</b> — all fields validated</span>,
    live: <span><b>Activated</b> — live for ordering</span>,
  }[p.stage];
  const cta = { intake: "Open intake", mkt: "Review", setup: "Set up", live: "View" }[p.stage];
  return (
    <button className="task" onClick={() => onOpen(p)}>
      <span className="t-stage" style={{ background: `var(${S.varName})` }}></span>
      <div className="t-main">
        <div className="t-name">{p.name}</div>
        <div className="t-meta">
          <span>{p.vendor}</span>
          <span>·</span>
          <Aging days={p.days} />
          {p.flags && p.flags.map((f, i) => <span key={i} className="tag warn">{f.text}</span>)}
        </div>
        <div className="t-ask">{ask}</div>
      </div>
      <div className="t-right">
        <Steps pct={p.progress} />
        <span className="btn btn-ghost btn-sm" style={{ pointerEvents: "none" }}>{cta} <Icon name="arrowRight" size={13} /></span>
      </div>
    </button>
  );
}

function ActivityFeed({ onOpen, products }) {
  const acts = window.HUB_DATA.GLOBAL_ACTIVITY;
  return (
    <div className="feed">
      {acts.map((a, i) => {
        const prod = products.find(p => p.name === a.target);
        return (
          <div className="feed-item" key={i}>
            <div className="fi-av"><Avatar name={a.who} size="sm" /></div>
            <div className="fi-body">
              <b>{a.who}</b> {a.text}{" "}
              {prod
                ? <b style={{ cursor: "pointer" }} onClick={() => onOpen(prod)} className="link-target">{a.target}</b>
                : <b>{a.target}</b>}
              {a.quote && <div className="fi-quote">“{a.quote}”</div>}
              <div className="fi-time">{a.time}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* role configuration for the home page */
function roleHome(role, products, me) {
  const D = window.HUB_DATA;
  const mine = (stage) => products.filter(p => p.stage === stage);
  switch (role) {
    case "purchaser":
      return {
        title: "Your products", greet: `Welcome back, ${me.name.split(" ")[0]}. Here's what needs you.`,
        queue: products.filter(p => p.stage === "intake"),
        queueTitle: "Needs you — in intake",
        stats: [
          { label: "In your intake", val: mine("intake").length, sub: `${mine("intake").filter(p => p.days >= 7).length} stalled 7+ days`, alert: true },
          { label: "With Marketing", val: mine("mkt").length, sub: "handed off, on track" },
          { label: "Activated (mo.)", val: mine("live").length, sub: "live for ordering", up: true },
        ],
        primaryCTA: true,
      };
    case "marketing":
      return {
        title: "Marketing review", greet: "Products that finished intake — review the AI drafts and approve.",
        queue: mine("mkt"), queueTitle: "Awaiting your review",
        stats: [
          { label: "In your queue", val: mine("mkt").length, sub: "ready to review" },
          { label: "AI-drafted", val: mine("mkt").length, sub: "naming + copy pre-filled", up: true },
          { label: "Sent to setup (mo.)", val: mine("setup").length + mine("live").length, sub: "approved & moved on" },
        ],
      };
    case "newitem":
      return {
        title: "PPRO setup queue", greet: "Approved products ready to set up and activate in PPRO.",
        queue: mine("setup"), queueTitle: "Ready for PPRO setup",
        stats: [
          { label: "Ready to set up", val: mine("setup").length, sub: `${mine("setup").filter(p => p.flags && p.flags.length).length} need attention`, alert: true },
          { label: "Activated (mo.)", val: mine("live").length, sub: "completed", up: true },
          { label: "Avg. days in setup", val: "2.4", sub: "down from 4.1" },
        ],
        export: true,
      };
    case "sales":
      return {
        title: "What's coming", greet: "Products in the pipeline you can pre-sell — and add account demand to.",
        queue: products.filter(p => p.stage !== "live"), queueTitle: "Coming soon — add demand",
        salesMode: true,
        stats: [
          { label: "In the pipeline", val: products.filter(p => p.stage !== "live").length, sub: "not yet live" },
          { label: "With your demand", val: products.filter(p => p.accounts && p.accounts.length).length, sub: "accounts attached", up: true },
          { label: "Activated (mo.)", val: mine("live").length, sub: "now sellable" },
        ],
      };
    case "warehouse":
      return {
        title: "Incoming items", greet: "Products approaching activation — verify dimensions and receiving.",
        queue: [...mine("setup"), ...mine("live")], queueTitle: "Incoming & recently activated",
        stats: [
          { label: "In setup", val: mine("setup").length, sub: "dimensions to verify" },
          { label: "Dimension flags", val: products.filter(p => p.flags && p.flags.length).length, sub: "need a check", alert: true },
          { label: "Activated (mo.)", val: mine("live").length, sub: "received" },
        ],
      };
    case "leadership":
      return {
        title: "Portfolio overview", greet: "Throughput and bottlenecks across every department.",
        queue: products.filter(p => p.days >= 7), queueTitle: "Bottlenecks — stalled 7+ days",
        stats: [
          { label: "In flight", val: products.filter(p => p.stage !== "live").length, sub: "across 4 stages" },
          { label: "Stalled 7+ days", val: products.filter(p => p.days >= 7).length, sub: "need escalation", alert: true },
          { label: "Activated (mo.)", val: mine("live").length, sub: "+18% vs last mo.", up: true },
          { label: "Avg. cycle time", val: "11d", sub: "intake → live" },
        ],
        leadership: true,
      };
    case "vendor":
      const own = products.filter(p => /fever/i.test(p.vendor));
      return {
        title: "Your items", greet: "Your products in the What Chefs Want onboarding pipeline.",
        queue: own, queueTitle: "Your submitted items", vendorMode: true,
        stats: [
          { label: "In progress", val: own.filter(p => p.stage !== "live").length, sub: "being onboarded" },
          { label: "Action needed", val: own.filter(p => p.flags && p.flags.length).length, sub: "info requested", alert: true },
          { label: "Live", val: own.filter(p => p.stage === "live").length, sub: "now orderable" },
        ],
      };
    default: return { title: "Home", queue: [], stats: [] };
  }
}

function HomeView({ products, role, me, onOpen, onStage, onNew, onAdvance, onExport, layout }) {
  const cfg = roleHome(role, products, me);
  const stalledCount = products.filter(p => p.stage === "intake" && p.days >= 7).length;
  return (
    <div className="page viewfade">
      <div className="page-head">
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Product Hub</div>
          <h1>{cfg.title}</h1>
          <div className="greet">{cfg.greet}</div>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          {cfg.export && <button className="btn btn-ghost" onClick={onExport}><Icon name="upload" size={15} /> Export PPRO CSV</button>}
          {cfg.primaryCTA && <button className="btn btn-primary btn-lg" onClick={onNew}><Icon name="plus" size={16} /> New Product</button>}
        </div>
      </div>

      {/* stats */}
      <div className="statline">
        {cfg.stats.map((s, i) => (
          <div className="stat" key={i}>
            <div className="s-label">{s.label}</div>
            <div className="s-val tnum" style={s.alert && Number(s.val) > 0 ? { color: "var(--red)" } : null}>{s.val}</div>
            <div className={`s-sub ${s.up ? "up" : ""}`}>{s.sub}</div>
          </div>
        ))}
      </div>

      <div className={`hub-grid ${layout === "stream" ? "stream" : ""}`}>
        <div>
          {/* stalled alert for purchaser/leadership */}
          {(role === "purchaser" || role === "leadership") && stalledCount > 0 && (
            <div className="alert-banner" style={{ marginBottom: 22 }}>
              <div className="ab-ico"><Icon name="clock" size={20} /></div>
              <div className="ab-body">
                <b>{stalledCount} products stalled 7+ days in intake</b>
                <p>Started but untouched since entry. A nudge keeps them moving.</p>
              </div>
              <button className="btn btn-dark btn-sm" onClick={() => onStage("intake")}>View stalled <Icon name="arrowRight" size={13} /></button>
            </div>
          )}

          <div className="sec-head">
            <h2>{cfg.queueTitle}</h2>
            <a className="sh-link" onClick={() => onStage(null)}>View all <Icon name="arrowRight" size={13} /></a>
          </div>

          {cfg.queue.length ? cfg.queue.map(p => (
            <Task key={p.id} p={p} role={role} onOpen={onOpen} onAdvance={onAdvance} />
          )) : (
            <div className="card card-pad empty">
              <div className="e-ico"><Icon name="check" size={28} /></div>
              <b>All clear</b>
              Nothing in this queue right now.
            </div>
          )}

          {/* pipeline flow */}
          <div className="sec-head" style={{ marginTop: 30 }}>
            <h2>Pipeline at a glance</h2>
            <a className="sh-link" onClick={() => onStage(null)}>Open board <Icon name="arrowRight" size={13} /></a>
          </div>
          <FlowStrip products={products} onStage={onStage} />
        </div>

        {/* right column */}
        <div className="hub-aside" style={layout === "stream" ? {} : { display: "flex", flexDirection: "column", gap: 22 }}>
          <div className="card card-pad">
            <div className="sec-head" style={{ margin: "0 0 8px" }}>
              <h2 style={{ fontSize: 15 }}>Recent activity</h2>
              <Icon name="activity" size={16} style={{ color: "var(--ink-3)" }} />
            </div>
            <ActivityFeed onOpen={onOpen} products={products} />
          </div>

          {role === "purchaser" && (
            <div className="card card-pad" style={{ background: "var(--surface-2)" }}>
              <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: "var(--surface)", border: "1px solid var(--red-line)", color: "var(--red)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                  <Icon name="sparkle" size={17} />
                </div>
                <div>
                  <b style={{ fontSize: 13.5 }}>Stuck on a field?</b>
                  <p style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 3, lineHeight: 1.5 }}>
                    Every field has a <b>Why?</b> explainer, and AI drafts the tricky classification and copy for you. You just describe the product.
                  </p>
                </div>
              </div>
            </div>
          )}

          {cfg.salesMode && (
            <div className="card card-pad">
              <div className="sec-head" style={{ margin: "0 0 10px" }}>
                <h2 style={{ fontSize: 15 }}>Top requested</h2>
                <Icon name="store" size={16} style={{ color: "var(--ink-3)" }} />
              </div>
              <div className="sales-strip">
                {products.filter(p => p.accounts && p.accounts.length).slice(0, 3).map(p => (
                  <div className="acct-row" key={p.id} style={{ cursor: "pointer" }} onClick={() => onOpen(p)}>
                    <div className="ar-logo">{p.name.split(" ")[0].slice(0, 2)}</div>
                    <div className="ar-main">
                      <div className="ar-name" style={{ fontSize: 12.5 }}>{p.name}</div>
                      <div className="ar-meta">{p.accounts.length} accounts waiting</div>
                    </div>
                    <StagePill stage={p.stage} />
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeView, FlowStrip, ActivityFeed });
