// Retail / Stores page — multi-store performance with retail-specific KPIs

const { useState: useStateRet, useMemo: useMemoRet } = React;

function StoresPage({ data, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { stores, pl } = data;
  const { curIdx, cmpIdx, sumAt, cmpMult, compareDeltaSub, PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);
  const [sortBy, setSortBy] = useStateRet("revPerSqft");
  const [groupBy, setGroupBy] = useStateRet("none");

  // Enrich each store with derived metrics
  const enriched = stores.map(s => {
    const profit = s.gp - s.opex;
    return {
      ...s,
      profit,
      gpPct: (s.gp / s.revenue) * 100,
      profitPct: (profit / s.revenue) * 100,
      revPerSqft: s.revenue / s.sqft,
      profitPerSqft: profit / s.sqft,
      revPerFte: s.revenue / s.fte,
      revPerHour: s.revenue / (s.hours * 4.33), // monthly hours
      conversion: ((s.revenue / (s.traffic * 32)) * 100), // avg ticket $32 baseline
      avgTicket: s.revenue / (s.traffic * 0.18), // 18% conversion baseline
    };
  });
  const sorted = [...enriched].sort((a, b) => b[sortBy] - a[sortBy]);
  const totals = enriched.reduce((acc, s) => ({
    revenue: acc.revenue + s.revenue,
    gp: acc.gp + s.gp,
    opex: acc.opex + s.opex,
    profit: acc.profit + s.profit,
    sqft: acc.sqft + s.sqft,
    traffic: acc.traffic + s.traffic,
    fte: acc.fte + s.fte,
  }), { revenue: 0, gp: 0, opex: 0, profit: 0, sqft: 0, traffic: 0, fte: 0 });

  const avgRevPerSqft = totals.revenue / totals.sqft;
  const compStoreSales = 4.2; // mock

  // Regional aggregation
  const byRegion = enriched.reduce((acc, s) => {
    if (!acc[s.region]) acc[s.region] = { region: s.region, stores: 0, revenue: 0, sqft: 0, profit: 0, traffic: 0 };
    acc[s.region].stores += 1;
    acc[s.region].revenue += s.revenue;
    acc[s.region].sqft += s.sqft;
    acc[s.region].profit += s.profit;
    acc[s.region].traffic += s.traffic;
    return acc;
  }, {});
  const regionList = Object.values(byRegion);

  const periodRev  = sumAt(pl.revenue, curIdx);
  const periodRevPrev = sumAt(pl.revenue, cmpIdx) * cmpMult;

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      {/* KPI strip */}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Stores" value={stores.length} hint={`${regionList.length} regions · ${totals.sqft.toLocaleString()} sqft`} accent="var(--accent)" />
        <KPICard label="Total revenue" value={fmtUSD(periodRev, { compact: true })} delta={periodRevPrev > 0 ? deltaPct(periodRev, periodRevPrev) : null} sub={compareDeltaSub || "vs. last period"} accent="var(--accent)" spark={pl.revenue} />
        <KPICard label="Comp store sales" value={"+" + compStoreSales + "%"} hint="Same-store, vs. last year" accent="var(--positive)" />
        <KPICard label="Avg revenue / sqft" value={fmtUSD(avgRevPerSqft, { decimals: 0 })} delta={2.8} sub={compareDeltaSub || "vs. last period"} accent="var(--accent-2)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>Store portfolio diagnosis</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              <b>Cherry Creek</b> is the only unprofitable location (-$5.3K this month). Foot traffic is 32% below the West region average — sub-prime block + nearby competitor opening explain most of it. Three options model out: relocate (12-mo payback), close (one-time $84K hit but $63K/yr saved), or reposition as outlet (likely +$48K revenue). <b>Pearl District</b> remains best $/sqft at <b>$83.9</b> — playbook worth replicating in new openings.
            </div>
          </div>
        </div>
        <button className="pc-btn-mini">Open Cherry Creek</button>
      </div>

      {/* Regional grid */}
      <div className="pc-grid-2">
        <Card title="Performance by region" subtitle="Revenue, traffic, and footprint">
          <table className="pc-table compact">
            <thead><tr><th>Region</th><th style={{textAlign:"right"}}>Stores</th><th style={{textAlign:"right"}}>Revenue</th><th style={{textAlign:"right"}}>$/sqft</th><th>Profit</th></tr></thead>
            <tbody>
              {regionList.map((r, i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontWeight: 500}}>{r.region}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{r.stores}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.revenue, {compact:true})}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.revenue / r.sqft, {decimals: 0})}</td>
                  <td>
                    <Bullet value={(r.profit / r.revenue) * 100} target={15} max={35} accent={r.profit > 0 ? "var(--positive)" : "var(--danger)"} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="Comp store sales — trailing 12 months" subtitle="Same-store growth vs prior year">
          <AreaChart
            height={220}
            yFmt={(v) => v.toFixed(1) + "%"}
            labels={pl.labels}
            series={[
              { name: "Comp %", values: [3.2, 3.8, 4.4, 5.1, 4.8, 4.4, 4.2, 3.9, 4.1, 4.6, 4.3, 4.2], color: "var(--positive)" },
              { name: "Target",  values: Array(12).fill(3.0), color: "var(--accent-2)", fill: false, dashed: true },
            ]}
          />
        </Card>
      </div>

      {/* Store performance table */}
      <Card title="Store performance" subtitle="Per-store KPIs · all locations"
            action={
              <div style={{ display: "flex", gap: 8 }}>
                <div className="pc-seg-sm">
                  {[
                    { k: "revPerSqft",    l: "$ / sqft" },
                    { k: "revenue",       l: "Revenue" },
                    { k: "profit",        l: "Profit" },
                    { k: "conversion",    l: "Conversion" },
                  ].map(s => <button key={s.k} className={sortBy === s.k ? "active" : ""} onClick={() => setSortBy(s.k)}>{s.l}</button>)}
                </div>
                <ExportButton rows={sorted} filename="Store_Performance" />
              </div>
            } padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>Store</th>
              <th>Region</th>
              <th style={{textAlign:"right"}}>Sqft</th>
              <th style={{textAlign:"right"}}>FTE</th>
              <th style={{textAlign:"right"}}>Traffic</th>
              <th style={{textAlign:"right"}}>Revenue</th>
              <th style={{textAlign:"right"}}>$/sqft</th>
              <th style={{textAlign:"right"}}>GM%</th>
              <th style={{textAlign:"right"}}>Opex</th>
              <th style={{textAlign:"right"}}>Profit</th>
              <th style={{textAlign:"right"}}>Profit %</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((s, i) => (
              <tr key={i} className={s.profit < 0 ? "pc-row-danger" : ""}>
                <td style={{paddingLeft:14}}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{s.name}</div>
                  <div style={{ fontFamily: "ui-monospace, monospace", fontSize: 10.5, color: "var(--text-3)" }}>{s.id} · Opened {s.opened}</div>
                </td>
                <td><span className="pc-chip">{s.region}</span></td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{s.sqft.toLocaleString()}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{s.fte}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--text-2)"}}>{s.traffic.toLocaleString()}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500}}>{fmtUSD(s.revenue, {compact:true})}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 600, color: s.revPerSqft > avgRevPerSqft ? "var(--positive)" : "var(--warning)"}}>{fmtUSD(s.revPerSqft, {decimals:0})}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{s.gpPct.toFixed(1)}%</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--text-2)"}}>{fmtUSD(s.opex, {compact:true})}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500, color: s.profit > 0 ? "var(--positive)" : "var(--danger)"}}>{fmtUSD(s.profit, {compact:true})}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: s.profitPct >= 15 ? "var(--positive)" : s.profitPct >= 5 ? "var(--warning)" : "var(--danger)"}}>{s.profitPct.toFixed(1)}%</td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr style={{ fontWeight: 600 }}>
              <td style={{paddingLeft:14}}>Portfolio total</td>
              <td></td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{totals.sqft.toLocaleString()}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{totals.fte}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{totals.traffic.toLocaleString()}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(totals.revenue, {compact:true})}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(totals.revenue / totals.sqft, {decimals: 0})}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{(totals.gp / totals.revenue * 100).toFixed(1)}%</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(totals.opex, {compact:true})}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--accent)"}}>{fmtUSD(totals.profit, {compact:true})}</td>
              <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--accent)"}}>{(totals.profit / totals.revenue * 100).toFixed(1)}%</td>
            </tr>
          </tfoot>
        </table>
      </Card>

      {/* Charts row: revenue per sqft + traffic vs conversion */}
      <div className="pc-grid-2">
        <Card title="Revenue per sqft" subtitle="Productivity ranking">
          <BarChart
            data={sorted.map((s, i) => ({ label: s.name.split("—")[0].trim().slice(0, 10), value: Math.round(s.revPerSqft) }))}
            colorFn={(d, i) => sorted[i].revPerSqft > avgRevPerSqft ? "var(--positive)" : "var(--warning)"}
            height={220}
            yFmt={(v) => "$" + v.toFixed(0)}
          />
        </Card>
        <Card title="Traffic → conversion" subtitle="Top of funnel · last 30 days">
          <table className="pc-table compact">
            <thead><tr><th>Store</th><th style={{textAlign:"right"}}>Traffic</th><th style={{textAlign:"right"}}>Avg ticket</th><th>Conversion</th></tr></thead>
            <tbody>
              {enriched.slice(0, 6).map((s, i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontSize: 12}}>{s.name.split("—")[0].trim()}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{s.traffic.toLocaleString()}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(s.avgTicket, {decimals: 0})}</td>
                  <td><Bullet value={s.conversion} target={20} max={50} accent={s.conversion >= 20 ? "var(--positive)" : "var(--warning)"} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      {/* Specialized retail KPIs */}
      <Card title="Operating KPIs · retail-specific" subtitle="Productivity, labor efficiency, and asset utilization">
        <div className="pc-drill-kpi-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
          {[
            { l: "Revenue / sqft / month", v: fmtUSD(avgRevPerSqft, {decimals: 0}), d: 2.8 },
            { l: "Revenue / FTE / month",  v: fmtUSD(totals.revenue / totals.fte, {compact:true}), d: 4.2 },
            { l: "Labor as % revenue",     v: ((totals.fte * 4800) / totals.revenue * 100).toFixed(1) + "%", d: -0.4 },
            { l: "Occupancy cost / sqft",  v: fmtUSD(38), d: 1.2 },
            { l: "Sales per labor hour",   v: fmtUSD(totals.revenue / (totals.fte * 160), {decimals: 0}), d: 2.1 },
            { l: "Inventory turns / year", v: "8.4x", d: -2.4 },
            { l: "Markdown %",             v: "4.2%", d: 1.1 },
            { l: "Shrink %",               v: "1.4%", d: -0.2 },
          ].map((k, i) => (
            <div key={i} className="pc-drill-kpi">
              <div className="pc-mk-l">{k.l}</div>
              <div className="pc-mk-v">{k.v}</div>
              <div className="pc-mk-d" style={{ color: k.d >= 0 ? "var(--positive)" : "var(--danger)" }}>
                {k.d >= 0 ? "▲" : "▼"} {Math.abs(k.d).toFixed(1)}%
              </div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { StoresPage });
