/* NutriDMS, Reporting & Analytics Engine (UI)
   Module shell + Executive Overview dashboard. Sales / Nutrition / Trends /
   Menu Performance / AI / Exports arrive in later chunks (placeholders here).
   Privacy-first, tier-gated, hand-built SVG charts. */

const { useState: useRpState, useEffect: useRpEffect, useMemo: useRpMemo } = React;

function rpFmtMoney(n) { return "$" + Math.round(n).toLocaleString(); }
function rpFmtK(n) { return n >= 1000 ? (n / 1000).toFixed(1) + "k" : String(Math.round(n)); }

/* ───────── Module shell ───────── */
function ReportsModule({ page }) {
  const { setPage } = useApp();
  const view = page === "reports" ? "overview" : page.split(":")[1];
  const [range, setRange] = useRpState(() => Number(window.__rptRange) || 30);
  const [location, setLocation] = useRpState(() => window.__rptLoc || "all");
  useRpEffect(() => { window.__rptRange = range; window.__rptLoc = location; }, [range, location]);

  const TABS = [
    { id: "overview", page: "reports", label: "Dashboard", icon: "layout-dashboard" },
    { id: "sales", page: "reports:sales", label: "Sales Intelligence", icon: "dollar-sign" },
    { id: "nutrition", page: "reports:nutrition", label: "Nutrition Intelligence", icon: "salad" },
    { id: "trends", page: "reports:trends", label: "Customer Intelligence", icon: "users" },
    { id: "menu-perf", page: "reports:menu", label: "Menu Intelligence", icon: "utensils-crossed" },
    { id: "health", page: "reports:health", label: "Health Intelligence", icon: "heart-pulse" },
    { id: "revenue", page: "reports:revenue", label: "Revenue Intelligence", icon: "trending-up" },
    { id: "campaign", page: "reports:campaign", label: "Campaign Intelligence", icon: "megaphone" },
    { id: "forecast", page: "reports:forecast", label: "Forecasting", icon: "line-chart" },
    { id: "benchmark", page: "reports:benchmark", label: "Benchmarking", icon: "gauge" },
    { id: "ai", page: "reports:ai", label: "AI Insights", icon: "lightbulb" },
    { id: "exec", page: "reports:exec", label: "Executive Dashboard", icon: "layout-dashboard" },
    { id: "personalized", page: "reports:personalized", label: "Customer Experience", icon: "heart-handshake" },
    { id: "exports", page: "reports:exports", label: "Exports", icon: "download" },
  ];
  const viewKey = ({ overview: "overview", sales: "sales", nutrition: "nutrition", trends: "trends", menu: "menu-perf", health: "health", revenue: "revenue", campaign: "campaign", forecast: "forecast", benchmark: "benchmark", ai: "ai", exec: "exec", personalized: "personalized", exports: "exports" })[view] || "overview";
  const opts = { range, location };

  const hasItems = (typeof rptMenuItems === "function") && rptMenuItems().length > 0;

  return (
    <div className="rp">
      <Crumbs path={[{ label: "Reports" }]} />
      <div className="page-head rp-head">
        <div>
          <h1 className="page-title">{TABS.find((t) => t.id === viewKey)?.label || "Reports"}</h1>
          <p className="page-sub">Privacy-first restaurant intelligence, anonymous, aggregated, decision-grade.</p>
        </div>
        <div className="rp-controls">
          <div className="rp-seg">
            {RPT_LOCATIONS.map((l) => <button key={l.id} className={location === l.id ? "on" : ""} onClick={() => setLocation(l.id)}>{l.label}</button>)}
          </div>
          <div className="rp-seg">
            {[{ v: 7, l: "7d" }, { v: 30, l: "30d" }, { v: 90, l: "90d" }].map((r) => <button key={r.v} className={range === r.v ? "on" : ""} onClick={() => setRange(r.v)}>{r.l}</button>)}
          </div>
        </div>
      </div>

      <div className="rp-privacy"><Icon name="shield-check" size={13} /> Privacy-first, every guest is an anonymous ID. No names, emails, or personal data are stored or shown.</div>

      {!hasItems ? (
        <div className="rp-empty"><div className="icon"><Icon name="bar-chart-3" size={26} /></div><h3>No published menu yet</h3><p>Publish recipes to start collecting sales and nutrition intelligence.</p></div>
      ) : !rptHasAccess(viewKey) ? (
        <RpLocked view={viewKey} setPage={setPage} />
      ) : (
        <>
          {viewKey === "overview" && <RpOverview opts={opts} setPage={setPage} />}
          {viewKey === "sales" && <RpSales opts={opts} />}
          {viewKey === "nutrition" && <RpNutrition opts={opts} />}
          {viewKey === "trends" && <RpTrends opts={opts} />}
          {viewKey === "menu-perf" && <RpMenuPerf opts={opts} />}
          {viewKey === "health" && <RpHealth opts={opts} />}
          {viewKey === "revenue" && <RpRevenue opts={opts} />}
          {viewKey === "campaign" && <RpCampaign opts={opts} />}
          {viewKey === "forecast" && <RpForecast opts={opts} />}
          {viewKey === "benchmark" && <RpBenchmark opts={opts} />}
          {viewKey === "exec" && <RpExec opts={opts} setPage={setPage} />}
          {viewKey === "personalized" && <RpPersonalized opts={opts} />}
          {viewKey === "ai" && <RpAiFull opts={opts} />}
          {viewKey === "exports" && <RpExports opts={opts} />}
          {viewKey !== "overview" && viewKey !== "sales" && viewKey !== "nutrition" && viewKey !== "trends" && viewKey !== "menu-perf" && viewKey !== "health" && viewKey !== "revenue" && viewKey !== "campaign" && viewKey !== "forecast" && viewKey !== "benchmark" && viewKey !== "exec" && viewKey !== "personalized" && viewKey !== "ai" && viewKey !== "exports" && <RpComingSoon label={TABS.find((t) => t.id === viewKey)?.label} />}
        </>
      )}
    </div>
  );
}

/* ───────── Tier lock ───────── */
function RpLocked({ view, setPage }) {
  const tier = rptTierLabel(view);
  return (
    <div className="rp-locked">
      <div className="rp-locked-badge"><Icon name="lock" size={26} /></div>
      <h2>{tier} feature</h2>
      <p>This dashboard is part of the <b>{tier}</b> plan. {tier === "Pro" ? "Nutrition consumption intelligence" : tier === "Enterprise" ? "AI & predictive analytics" : "Sales reporting"} unlocks deeper decision-grade insight.</p>
      <button className="btn primary" onClick={() => setPage("settings")}><Icon name="arrow-up-circle" size={16} /> Upgrade plan</button>
    </div>
  );
}
function RpComingSoon({ label }) {
  return (
    <div className="rp-empty"><div className="icon"><Icon name="hammer" size={24} /></div><h3>{label}, next build</h3><p>The {label} dashboard is part of this module and arrives in the next chunk. The Executive Dashboard is live now.</p></div>
  );
}

/* ───────── Executive Overview ───────── */
function RpOverview({ opts, setPage }) {
  const kpis = rptKpis(opts);
  const series = rptDailySeries(opts);
  const items = rptByItem(opts);
  const nutr = rptNutrition(opts);
  const top5 = items.slice(0, 5);
  const low = items.slice(-3).reverse();
  const ai = rptAiInsights(opts);

  return (
    <>
      <div className="rp-kpis">
        <RpKpi label="Revenue" value={rpFmtMoney(kpis.revenue)} icon="dollar-sign" tone="brand" trend={kpis.growth} trendLabel="vs prev. period" />
        <RpKpi label="Orders" value={kpis.orders.toLocaleString()} icon="receipt" tone="violet" />
        <RpKpi label="Avg order value" value={"$" + kpis.aov.toFixed(2)} icon="trending-up" tone="amber" />
        <RpKpi label="Top item" value={top5[0] ? top5[0].name : "—"} icon="award" tone="green" small />
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card rp-col-wide">
          <div className="rp-card-h"><div><h3>Revenue trend</h3><span>Daily revenue · last {opts.range} days</span></div>
            <div className="rp-legend"><span><i className="rp-dot brand" /> Revenue</span></div>
          </div>
          <RpAreaChart data={series} xKey="date" yKey="revenue" />
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Nutrition snapshot</h3><span>Per order, this period</span></div></div>
          <div className="rp-nutri">
            <div className="rp-nutri-row"><span>Avg calories</span><b>{nutr.avgCalories} kcal</b></div>
            <div className="rp-macrobar">
              <span className="rp-mb protein" style={{ flex: Math.max(nutr.avgProtein, 1) }} title="Protein" />
              <span className="rp-mb carbs" style={{ flex: Math.max(nutr.avgCarbs, 1) }} title="Carbs" />
              <span className="rp-mb fat" style={{ flex: Math.max(nutr.avgFat, 1) }} title="Fat" />
            </div>
            <div className="rp-macro-legend">
              <span><i className="rp-dot protein" /> Protein {nutr.avgProtein}g</span>
              <span><i className="rp-dot carbs" /> Carbs {nutr.avgCarbs}g</span>
              <span><i className="rp-dot fat" /> Fat {nutr.avgFat}g</span>
            </div>
            <div className="rp-nutri-tags">
              {nutr.tags.slice(0, 3).map((t) => <div key={t.label} className="rp-tagrow"><span>{t.label}</span><b>{t.pct}%</b></div>)}
            </div>
            <div className={`rp-sodium ${nutr.avgSodium > 700 ? "warn" : "ok"}`}>
              <Icon name={nutr.avgSodium > 700 ? "alert-triangle" : "check-circle-2"} size={13} /> Avg sodium {nutr.avgSodium} mg{nutr.avgSodium > 700 ? ", trending high" : ", within range"}
            </div>
          </div>
        </div>
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Top 5 menu items</h3><span>By revenue</span></div>
            <button className="rp-link" onClick={() => setPage("reports:sales")}>Sales report <Icon name="arrow-right" size={13} /></button>
          </div>
          <div className="rp-rank">
            {top5.map((it, i) => (
              <div key={it.itemId} className="rp-rank-row">
                <span className="rp-rank-n">{i + 1}</span>
                <span className="rp-rank-nm">{it.name}</span>
                <span className="rp-rank-bar"><i style={{ width: (it.revenue / (top5[0].revenue || 1)) * 100 + "%" }} /></span>
                <span className="rp-rank-v">{rpFmtMoney(it.revenue)}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Low performers</h3><span>Need attention</span></div></div>
          <div className="rp-rank">
            {low.map((it) => (
              <div key={it.itemId} className="rp-rank-row">
                <span className="rp-rank-nm">{it.name}</span>
                <span className="rp-rank-meta">{it.units} units</span>
                <span className="rp-rank-v dim">{rpFmtMoney(it.revenue)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <RpAiPanel insights={ai} />
    </>
  );
}

/* ───────── KPI tile ───────── */
function RpKpi({ label, value, icon, tone, trend, trendLabel, small }) {
  return (
    <div className="rp-kpi">
      <div className={`rp-kpi-ic ${tone}`}><Icon name={icon} size={18} /></div>
      <div className="rp-kpi-label">{label}</div>
      <div className={`rp-kpi-value ${small ? "sm" : ""}`}>{value}</div>
      {trend != null && (
        <div className={`rp-kpi-trend ${trend >= 0 ? "up" : "down"}`}>
          <Icon name={trend >= 0 ? "trending-up" : "trending-down"} size={13} stroke={2.5} />
          {Math.abs(trend).toFixed(1)}% <span>{trendLabel}</span>
        </div>
      )}
    </div>
  );
}

/* ───────── AI insights panel (always visible, Apply/Dismiss) ───────── */
function RpAiPanel({ insights }) {
  const { toast } = useApp();
  const [dismissed, setDismissed] = useRpState([]);
  const live = insights.filter((i) => !dismissed.includes(i.id));
  const enterprise = rptPlanRank() >= 2;
  return (
    <div className="rp-ai">
      <div className="rp-ai-h">
        <span className="rp-ai-title"><span className="rp-ai-spark"><Icon name="lightbulb" size={14} /></span> AI Insights</span>
        <span className="pill neutral" style={{ fontSize: 10 }}>{enterprise ? "Enterprise" : "Preview"}</span>
      </div>
      {live.length === 0 ? (
        <div className="rp-ai-empty">No active insights, everything looks healthy for this period.</div>
      ) : (
        <div className="rp-ai-list">
          {live.map((i) => (
            <div key={i.id} className={`rp-ai-item ${i.type}`}>
              <div className="rp-ai-ic"><Icon name={i.icon} size={15} /></div>
              <div className="rp-ai-tx">{i.text}</div>
              <div className="rp-ai-actions">
                <button className="rp-ai-apply" disabled={!enterprise} title={enterprise ? "" : "Enterprise plan applies suggestions automatically"} onClick={() => { toast(`Applied: ${i.action}`); setDismissed((d) => [...d, i.id]); }}>{i.action}</button>
                <button className="rp-ai-dismiss" onClick={() => setDismissed((d) => [...d, i.id])} aria-label="Dismiss"><Icon name="x" size={14} /></button>
              </div>
            </div>
          ))}
        </div>
      )}
      {!enterprise && <div className="rp-ai-foot"><Icon name="lock" size={11} /> One-click apply is an Enterprise feature. Insights are read-only on your plan.</div>}
    </div>
  );
}

/* ═══════════════════ Personalized Nutrition Experience (PRD Module 4, Premium) ═══════════════════ */
function RpPersonalized({ opts }) {
  const profiles = Object.keys(RPT_PROFILES);
  const [profile, setProfile] = useRpState("weight-loss");
  const ALLERGENS = ["Milk", "Egg", "Wheat", "Soy", "Peanut", "Tree nut", "Fish", "Shellfish", "Gluten"];
  const [allergies, setAllergies] = useRpState([]);
  const toggleA = (a) => setAllergies((s) => s.includes(a) ? s.filter((x) => x !== a) : [...s, a]);
  const menu = rptPersonalizedMenu(profile, allergies);
  const counts = { recommended: 0, caution: 0, avoid: 0 };
  menu.forEach((m) => counts[m.verdict]++);
  const p = RPT_PROFILES[profile];
  const vMeta = {
    recommended: { label: "Recommended", icon: "check-circle-2", cls: "rec" },
    caution: { label: "Use Caution", icon: "alert-triangle", cls: "cau" },
    avoid: { label: "Avoid", icon: "x-circle", cls: "avo" },
  };
  return (
    <>
      <div className="rp-pn-intro">
        <Icon name="heart-handshake" size={15} /> Customer-facing preview, how a guest with a saved health profile sees your menu. Guidance combines nutrition values, allergies, and your organization's health-condition rules.
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Health profile</h3><span>Optional guest account</span></div></div>
        <div className="rp-pn-profiles">
          {profiles.map((k) => (
            <button key={k} className={`rp-pn-profile ${profile === k ? "on" : ""}`} onClick={() => setProfile(k)}>
              <Icon name={RPT_PROFILES[k].icon} size={16} /> {RPT_PROFILES[k].label}
            </button>
          ))}
        </div>
        <div className="rp-pn-allg-lbl">Allergies (hard-avoid)</div>
        <div className="rp-pn-allg">
          {ALLERGENS.map((a) => <button key={a} className={`rp-pn-allg-chip ${allergies.includes(a) ? "on" : ""}`} onClick={() => toggleA(a)}>{allergies.includes(a) && <Icon name="check" size={11} />} {a}</button>)}
        </div>
      </div>

      <div className="rp-pn-summary">
        <div className="rp-pn-sum rec"><Icon name="check-circle-2" size={16} /> <b>{counts.recommended}</b> Recommended</div>
        <div className="rp-pn-sum cau"><Icon name="alert-triangle" size={16} /> <b>{counts.caution}</b> Use Caution</div>
        <div className="rp-pn-sum avo"><Icon name="x-circle" size={16} /> <b>{counts.avoid}</b> Avoid</div>
      </div>

      <div className="rp-pn-grid">
        {menu.map((m) => {
          const v = vMeta[m.verdict]; const it = m.item;
          return (
            <div key={it.id} className={`rp-pn-dish ${v.cls}`}>
              <div className="rp-pn-dish-h">
                <span className="rp-pn-dish-nm">{it.name}</span>
                <span className={`rp-pn-badge ${v.cls}`}><Icon name={v.icon} size={12} /> {v.label}</span>
              </div>
              <div className="rp-pn-macros">
                <span>{it.calories} kcal</span><span>P {it.protein}g</span><span>C {it.carbs}g</span><span>F {it.fat}g</span>
                <span>Fiber {it.fiber || 0}g</span><span>Na {it.sodium || 0}mg</span>
              </div>
              <ul className="rp-pn-reasons">
                {m.reasons.map((r, i) => <li key={i}><Icon name="dot" size={12} /> {r}</li>)}
              </ul>
            </div>
          );
        })}
      </div>
      <div className="rp-pn-foot"><Icon name="info" size={12} /> Guidance for the “{p.label}” profile is informational and does not replace medical advice.</div>
    </>
  );
}

/* ═══════════════════ Executive Dashboard (PRD Module 5, Enterprise) ═══════════════════ */
function RpExec({ opts, setPage }) {
  const kpis = rptKpis(opts);
  const rev = rptRevenueIntel(opts);
  const eng = rptEngagementTotals(opts);
  const cust = rptCustomers(opts);
  const cx = rptCxScore(opts);
  const interest = rptHealthInterest(opts)[0];
  const topItem = rptByItem(opts)[0];
  const ai = rptAiInsights(opts).slice(0, 3);
  const cxTone = cx.score >= 70 ? "ok" : cx.score >= 45 ? "mid" : "warn";
  const C = 2 * Math.PI * 52;
  const parts = [
    { label: "Nutrition views", v: cx.parts.nutrition, color: "#2f6b18" },
    { label: "QR engagement", v: cx.parts.qr, color: "#6938EF" },
    { label: "Loraa engagement", v: cx.parts.loraa, color: "#B54708" },
    { label: "Repeat visits", v: cx.parts.repeat, color: "#0E7490" },
  ];
  return (
    <>
      <div className="rp-exec-top">
        <div className="rp-card rp-cx">
          <div className="rp-card-h"><div><h3>Customer Experience Score</h3><span>Nutrition + QR + Loraa + loyalty</span></div></div>
          <div className="rp-cx-body">
            <div className={`rp-cx-ring ${cxTone}`}>
              <svg viewBox="0 0 120 120" width="124" height="124">
                <circle cx="60" cy="60" r="52" fill="none" stroke="var(--gray-100)" strokeWidth="10" />
                <circle cx="60" cy="60" r="52" fill="none" strokeWidth="10" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - cx.score / 100)} transform="rotate(-90 60 60)" className="rp-cx-arc" />
                <text x="60" y="56" textAnchor="middle" fontSize="30" fontWeight="800" fill="var(--gray-900)">{cx.score}</text>
                <text x="60" y="76" textAnchor="middle" fontSize="10" fontWeight="600" fill="var(--gray-500)">/ 100</text>
              </svg>
            </div>
            <div className="rp-cx-parts">
              {parts.map((p) => (
                <div key={p.label} className="rp-cx-part">
                  <span className="rp-cx-part-lbl">{p.label}</span>
                  <span className="rp-cx-track"><i style={{ width: p.v + "%", background: p.color }} /></span>
                  <span className="rp-cx-part-v">{p.v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="rp-exec-highlights">
          <div className="rp-exec-hl"><span className="rp-exec-hl-ic" style={{ background: "#E8F2DD", color: "#2f6b18" }}><Icon name="trending-up" size={16} /></span><div><span className="rp-exec-hl-l">Top health trend</span><b>{interest ? interest.label : "High Protein"}</b></div></div>
          <div className="rp-exec-hl"><span className="rp-exec-hl-ic" style={{ background: "#FDF1DC", color: "#B54708" }}><Icon name="award" size={16} /></span><div><span className="rp-exec-hl-l">Top menu item</span><b>{topItem ? topItem.name : "—"}</b></div></div>
          <div className="rp-exec-hl"><span className="rp-exec-hl-ic" style={{ background: "#F1ECFE", color: "#6938EF" }}><Icon name="users" size={16} /></span><div><span className="rp-exec-hl-l">Returning guests</span><b>{cust.returningPct}%</b></div></div>
          <div className="rp-exec-hl"><span className="rp-exec-hl-ic" style={{ background: "#DCF5E6", color: "#157347" }}><Icon name="salad" size={16} /></span><div><span className="rp-exec-hl-l">Nutrition engagement</span><b>{eng.nutritionEngagementRate}%</b></div></div>
        </div>
      </div>

      <div className="rp-kpis">
        <RpKpi label="Revenue" value={rpFmtMoney(kpis.revenue)} icon="dollar-sign" tone="brand" trend={kpis.growth} trendLabel="vs prev." />
        <RpKpi label="Margin" value={rev.margin + "%"} icon="percent" tone="green" />
        <RpKpi label="Orders" value={kpis.orders.toLocaleString()} icon="receipt" tone="violet" />
        <RpKpi label="Healthy revenue" value={rev.healthyPct + "%"} icon="leaf" tone="amber" />
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>AI recommendations</h3><span>Top actions this period</span></div>
          <button className="rp-link" onClick={() => setPage("reports:ai")}>Open advisor <Icon name="arrow-right" size={13} /></button>
        </div>
        <div className="rp-exec-recs">
          {ai.map((i) => (
            <div key={i.id} className={`rp-exec-rec ${i.type}`}>
              <span className="rp-exec-rec-ic"><Icon name={i.icon} size={15} /></span>
              <span className="rp-exec-rec-tx">{i.text}</span>
            </div>
          ))}
          {ai.length === 0 && <div className="rp-chart-empty">No recommendations, performance looks healthy.</div>}
        </div>
      </div>
    </>
  );
}

/* ═══════════════════ AI Insights + Loraa Restaurant Advisor (Enterprise) ═══════════════════ */
function RpAdvisor({ opts }) {
  const cats = Object.keys(RPT_ADVISOR);
  const [cat, setCat] = useRpState("business");
  const [asked, setAsked] = useRpState(null);
  const c = RPT_ADVISOR[cat];
  const ask = (q) => setAsked({ q, a: rptAdvisorAnswer(q, opts) });
  return (
    <div className="rp-adv">
      <div className="rp-adv-h">
        <span className="rp-ai-title"><span className="rp-ai-spark"><Icon name="lightbulb" size={14} /></span> Loraa Restaurant Advisor</span>
        <span className="pill neutral" style={{ fontSize: 10 }}>Enterprise</span>
      </div>
      <div className="rp-adv-cats">
        {cats.map((k) => (
          <button key={k} className={`rp-adv-cat ${cat === k ? "on" : ""}`} onClick={() => { setCat(k); setAsked(null); }}>
            <Icon name={RPT_ADVISOR[k].icon} size={14} /> {RPT_ADVISOR[k].label}
          </button>
        ))}
      </div>
      <div className="rp-adv-body">
        <div className="rp-adv-qs">
          {c.questions.map((q) => (
            <button key={q} className={`rp-adv-q ${asked && asked.q === q ? "on" : ""}`} onClick={() => ask(q)}>
              <Icon name="message-circle" size={13} /> {q}
            </button>
          ))}
        </div>
        {asked ? (
          <div className="rp-adv-answer">
            <div className="rp-adv-q-echo"><Icon name="help-circle" size={14} /> {asked.q}</div>
            <div className="rp-adv-a">
              <span className="rp-ai-spark sm"><Icon name="lightbulb" size={12} /></span>
              <div>
                <p className="rp-adv-finding">{asked.a.finding}</p>
                {asked.a.detail && <p className="rp-adv-detail">{asked.a.detail}</p>}
                {asked.a.rec && <div className="rp-adv-rec"><Icon name="lightbulb" size={13} /> <span><b>Recommendation:</b> {asked.a.rec}</span></div>}
              </div>
            </div>
          </div>
        ) : (
          <div className="rp-adv-placeholder"><Icon name="lightbulb" size={20} /><p>Ask a {c.label.replace(" Advisor", "")} question, Loraa answers from your live data.</p></div>
        )}
      </div>
    </div>
  );
}

/* ═══════════════════ AI Insights (full page, Enterprise) ═══════════════════ */
function RpAiFull({ opts }) {
  const ai = rptAiInsights(opts);
  const groups = [
    { id: "opportunity", label: "Opportunities", icon: "trending-up" },
    { id: "warning", label: "Warnings", icon: "alert-triangle" },
    { id: "suggestion", label: "Suggestions", icon: "lightbulb" },
    { id: "insight", label: "Behavioral insights", icon: "repeat" },
  ];
  return (
    <>
      <RpAdvisor opts={opts} />
      {groups.map((g) => {
        const list = ai.filter((i) => i.type === g.id);
        if (!list.length) return null;
        return (
          <div key={g.id} className="rp-card">
            <div className="rp-card-h"><div><h3>{g.label}</h3><span>{list.length} insight{list.length === 1 ? "" : "s"}</span></div></div>
            <RpAiPanel insights={list} />
          </div>
        );
      })}
    </>
  );
}

/* ═══════════════════ Exports (PRD §8) ═══════════════════ */
function RpExports({ opts }) {
  const { toast } = useApp();
  const [type, setType] = useRpState("sales");
  const [fmt, setFmt] = useRpState("csv");
  const TYPES = [
    { id: "sales", label: "Sales", icon: "dollar-sign", tier: "sales" },
    { id: "nutrition", label: "Nutrition", icon: "salad", tier: "nutrition" },
    { id: "trends", label: "Customer Trends", icon: "users", tier: "trends" },
    { id: "menu", label: "Menu Performance", icon: "utensils-crossed", tier: "menu-perf" },
  ];
  const FMTS = [{ id: "pdf", label: "PDF", icon: "file-text" }, { id: "excel", label: "Excel", icon: "sheet" }, { id: "csv", label: "CSV", icon: "file-spreadsheet" }];
  const tierOk = rptHasAccess(TYPES.find((t) => t.id === type).tier);
  const dl = (name, blob) => { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000); };

  const generate = () => {
    if (!tierOk) { toast("Upgrade your plan to export this report"); return; }
    const t = TYPES.find((x) => x.id === type);
    const stamp = new Date().toISOString().slice(0, 10);
    const base = `nutridms-${type}-report-${stamp}`;
    if (fmt === "csv" || fmt === "excel") {
      const csv = rptToCsv(type, opts);
      dl(`${base}.${fmt === "excel" ? "xls" : "csv"}`, new Blob([csv], { type: fmt === "excel" ? "application/vnd.ms-excel" : "text/csv" }));
    } else {
      dl(`${base}.html`, new Blob([rpExportHtml(t, opts)], { type: "text/html" }));
    }
    toast(`${t.label} report exported (${fmt.toUpperCase()})`);
  };

  const preview = rptExportRows(type, opts);
  return (
    <div className="rp-row rp-row-2">
      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Generate report</h3><span>Privacy-safe · aggregated data only</span></div></div>
        <div className="rp-exp-lbl">Report type</div>
        <div className="rp-exp-grid">
          {TYPES.map((t) => {
            const locked = !rptHasAccess(t.tier);
            return (
              <button key={t.id} className={`rp-exp-opt ${type === t.id ? "on" : ""} ${locked ? "locked" : ""}`} onClick={() => setType(t.id)}>
                <Icon name={t.icon} size={16} /> {t.label}
                {locked && <Icon name="lock" size={12} className="rp-exp-lock" />}
              </button>
            );
          })}
        </div>
        <div className="rp-exp-lbl">Format</div>
        <div className="rp-exp-grid fmts">
          {FMTS.map((f) => <button key={f.id} className={`rp-exp-opt ${fmt === f.id ? "on" : ""}`} onClick={() => setFmt(f.id)}><Icon name={f.icon} size={16} /> {f.label}</button>)}
        </div>
        <button className="btn primary rp-exp-go" disabled={!tierOk} onClick={generate}><Icon name="download" size={16} /> {tierOk ? "Generate report" : `${rptTierLabel(TYPES.find((t) => t.id === type).tier)} plan required`}</button>
        <div className="rp-exp-note"><Icon name="shield-check" size={12} /> Exports contain only aggregated, anonymous data, never personal identifiers.</div>
      </div>
      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Preview</h3><span>{preview.rows.length} rows · {opts.range}-day window</span></div></div>
        {tierOk ? (
          <div className="rp-exp-preview">
            <table className="rp-table">
              <thead><tr>{preview.headers.map((h) => <th key={h}>{h}</th>)}</tr></thead>
              <tbody>{preview.rows.slice(0, 8).map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j}>{c}</td>)}</tr>)}</tbody>
            </table>
            {preview.rows.length > 8 && <div className="rp-exp-more">+ {preview.rows.length - 8} more rows in the export</div>}
          </div>
        ) : <div className="rp-chart-empty" style={{ padding: "30px 0" }}>Upgrade to preview and export this report.</div>}
      </div>
    </div>
  );
}
function rpExportHtml(t, opts) {
  const { headers, rows } = rptExportRows(t.id, opts);
  const k = rptKpis(opts);
  const stamp = new Date().toLocaleString();
  return `<!doctype html><html><head><meta charset="utf-8"><title>${t.label} report</title>
<style>body{font-family:-apple-system,Segoe UI,Roboto,sans-serif;color:#1a2218;max-width:840px;margin:0 auto;padding:32px}
h1{font-size:24px;margin:0 0 2px}.sub{color:#5a6657;font-size:13px;margin-bottom:18px}
.kpis{display:flex;gap:18px;margin:18px 0;flex-wrap:wrap}.kpi{flex:1;min-width:120px;border:1px solid #d8e0d2;border-radius:10px;padding:12px}
.kpi b{display:block;font-size:20px}.kpi span{font-size:11px;color:#5a6657;text-transform:uppercase}
table{width:100%;border-collapse:collapse;font-size:12px;margin-top:14px}th{text-align:left;background:#f1f6ea;padding:8px;border-bottom:2px solid #2f6b18}
td{padding:7px 8px;border-bottom:1px solid #eee}.foot{margin-top:20px;font-size:10px;color:#9aa595}
.print{position:fixed;top:16px;right:16px;background:#2f6b18;color:#fff;border:0;border-radius:999px;padding:9px 16px;font-weight:700;cursor:pointer}
@media print{.print{display:none}}</style></head><body>
<button class="print" onclick="window.print()">Print / Save PDF</button>
<h1>${t.label} Report</h1><div class="sub">NutriDMS · ${opts.range}-day window · generated ${stamp}</div>
<div class="kpis"><div class="kpi"><span>Revenue</span><b>$${Math.round(k.revenue).toLocaleString()}</b></div><div class="kpi"><span>Orders</span><b>${k.orders.toLocaleString()}</b></div><div class="kpi"><span>Avg order</span><b>$${k.aov.toFixed(2)}</b></div></div>
<table><thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`).join("")}</tbody></table>
<div class="foot">Privacy-first export, aggregated, anonymous data only. No personal identifiers. © NutriDMS.</div></body></html>`;
}

/* ═══════════════════ Benchmarking (PRD §13, Enterprise) ═══════════════════ */
function RpBenchmark({ opts }) {
  const rows = rptBenchmark(opts);
  const wins = rows.filter((r) => r.better).length;
  const fmt = (r, v) => (r.money ? "$" + v : v.toLocaleString()) + (r.unit || "");
  return (
    <>
      <div className="rp-bench-hero">
        <div className="rp-bench-score">
          <div className="rp-bench-score-v">{wins}<span>/ {rows.length}</span></div>
          <div className="rp-bench-score-l">metrics ahead of industry</div>
        </div>
        <div className="rp-bench-note"><Icon name="shield-check" size={14} /> Compared against an anonymous aggregate of similar restaurants. No competitor is ever identified, benchmarks are pooled and privacy-safe.</div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>You vs. industry</h3><span>Anonymous peer comparison · {opts.range}-day window</span></div></div>
        <div className="rp-bench-list">
          {rows.map((r) => {
            const max = Math.max(r.you, r.industry) * 1.1 || 1;
            return (
              <div key={r.label} className="rp-bench-row">
                <div className="rp-bench-lbl">{r.label}
                  <span className={`rp-bench-tag ${r.better ? "win" : "lose"}`}>{r.better ? "Ahead" : "Behind"} {r.deltaPct > 0 ? "+" : ""}{r.deltaPct}%</span>
                </div>
                <div className="rp-bench-bars">
                  <div className="rp-bench-track"><i className="you" style={{ width: (r.you / max) * 100 + "%" }} /><span className="rp-bench-val">You {fmt(r, r.you)}</span></div>
                  <div className="rp-bench-track"><i className="ind" style={{ width: (r.industry / max) * 100 + "%" }} /><span className="rp-bench-val ind">Industry {fmt(r, r.industry)}</span></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

/* ═══════════════════ Forecasting (PRD §13, Enterprise) ═══════════════════ */
function RpForecast({ opts }) {
  const f = rptForecast(opts);
  const demands = [
    { label: "Revenue (monthly)", pct: f.monthlyGrowthPct, icon: "dollar-sign" },
    { label: "Protein demand", pct: f.proteinDemand, icon: "beef" },
    { label: "Low-carb demand", pct: f.lowCarbDemand, icon: "wheat-off" },
    { label: "High-fiber demand", pct: f.fiberDemand, icon: "sprout" },
    { label: "Plant-based demand", pct: f.plantDemand, icon: "leaf" },
  ];
  return (
    <>
      <div className="rp-kpis">
        <RpKpi label="30-day revenue" value={rpFmtMoney(f.revenue.d30)} icon="calendar" tone="brand" />
        <RpKpi label="60-day revenue" value={rpFmtMoney(f.revenue.d60)} icon="calendar" tone="violet" />
        <RpKpi label="90-day revenue" value={rpFmtMoney(f.revenue.d90)} icon="calendar" tone="amber" />
        <RpKpi label="Model confidence" value={f.confidence + "%"} icon="gauge" tone="green" />
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Revenue forecast</h3><span>90-day history → 30-day projection</span></div>
          <div className="rp-legend"><span><i className="rp-dot brand" /> Actual</span><span><i className="rp-dot" style={{ background: "#9171f0", borderRadius: 3 }} /> Forecast</span></div>
        </div>
        <RpForecastChart f={f} />
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Predicted demand trends</h3><span>Projected 30-day change by health angle</span></div></div>
        <div className="rp-demands">
          {demands.map((d) => (
            <div key={d.label} className="rp-demand">
              <span className="rp-demand-ic"><Icon name={d.icon} size={15} /></span>
              <span className="rp-demand-lbl">{d.label}</span>
              <span className={`rp-demand-pct ${d.pct > 0 ? "up" : d.pct < 0 ? "down" : ""}`}>
                <Icon name={d.pct > 0 ? "trending-up" : d.pct < 0 ? "trending-down" : "minus"} size={13} stroke={2.5} />
                {d.pct > 0 ? "+" : ""}{d.pct}%
              </span>
            </div>
          ))}
        </div>
        <div className="rp-camp-insight"><Icon name="lightbulb" size={13} /> {f.proteinDemand > 10 ? `High-protein demand is projected to rise ${f.proteinDemand}%, ensure adequate high-protein menu coverage.` : "Demand trends are stable across health angles for the coming month."}</div>
      </div>
    </>
  );
}

/* forecast chart: actual history + dashed projection */
function RpForecastChart({ f }) {
  const hist = f.series.map((d, i) => ({ x: i, y: d.revenue }));
  if (hist.length < 2) return <div className="rp-chart-empty">Not enough history to forecast.</div>;
  const FUT = 30, W = 760, H = 230, P = 30;
  const allMax = Math.max(...hist.map((p) => p.y), f.dayRev(f.lastX + FUT)) * 1.1 || 1;
  const totalX = hist.length - 1 + FUT;
  const x = (i) => P + (i / totalX) * (W - P * 2);
  const y = (v) => H - P - (v / allMax) * (H - P * 2);
  const histLine = hist.map((p, i) => `${i === 0 ? "M" : "L"}${x(i).toFixed(1)},${y(p.y).toFixed(1)}`).join(" ");
  const histArea = `${histLine} L${x(hist.length - 1).toFixed(1)},${H - P} L${x(0).toFixed(1)},${H - P} Z`;
  const fut = [];
  for (let i = 0; i <= FUT; i++) { const xi = f.lastX + i; fut.push(`${i === 0 ? "M" : "L"}${x(hist.length - 1 + i).toFixed(1)},${y(f.dayRev(xi)).toFixed(1)}`); }
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="rp-chart" preserveAspectRatio="none">
      <defs><linearGradient id="rpFc" x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stopColor="#2f6b18" stopOpacity=".22" /><stop offset="100%" stopColor="#2f6b18" stopOpacity="0" /></linearGradient></defs>
      {[0, .25, .5, .75, 1].map((t, i) => <line key={i} x1={P} x2={W - P} y1={P + t * (H - P * 2)} y2={P + t * (H - P * 2)} stroke="var(--gray-100)" strokeWidth="1" />)}
      <line x1={x(hist.length - 1)} x2={x(hist.length - 1)} y1={P} y2={H - P} stroke="var(--gray-200)" strokeWidth="1" strokeDasharray="3 3" />
      <path d={histArea} fill="url(#rpFc)" />
      <path d={histLine} fill="none" stroke="#2f6b18" strokeWidth="2.5" strokeLinejoin="round" />
      <path d={fut.join(" ")} fill="none" stroke="#9171f0" strokeWidth="2.5" strokeDasharray="5 4" strokeLinejoin="round" />
    </svg>
  );
}

/* ═══════════════════ Campaign Intelligence (PRD §12, Pro) ═══════════════════ */
function RpCampaign({ opts }) {
  const camps = rptCampaigns(opts);
  const [sel, setSel] = useRpState(0);
  const c = camps[sel] || camps[0];
  if (!c) return <div className="rp-empty"><div className="icon"><Icon name="megaphone" size={24} /></div><h3>No active campaigns</h3><p>Campaigns built around health angles will appear here with their full funnel.</p></div>;
  const funnel = [
    { label: "Views", value: c.views, icon: "eye", tone: "brand" },
    { label: "Nutrition engagement", value: c.nutritionEng, icon: "salad", tone: "violet" },
    { label: "Orders", value: c.orders, icon: "receipt", tone: "amber" },
  ];
  const maxF = Math.max(...funnel.map((f) => f.value), 1);
  return (
    <>
      <div className="rp-camp-tabs">
        {camps.map((cm, i) => (
          <button key={cm.id} className={`rp-camp-tab ${i === sel ? "on" : ""}`} onClick={() => setSel(i)}>
            <span className={`rp-camp-dot ${cm.status}`} /> {cm.name}
            <span className="rp-camp-rev">{rpFmtMoney(cm.revenue)}</span>
          </button>
        ))}
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>{c.name}</h3><span>{c.channel} · {c.status === "active" ? "Active" : "Ended"} · {c.items} item(s)</span></div></div>
          <div className="rp-funnel">
            {funnel.map((f, i) => (
              <div key={f.label} className="rp-funnel-stage">
                <div className="rp-funnel-bar-wrap">
                  <div className={`rp-funnel-bar ${f.tone}`} style={{ width: Math.max((f.value / maxF) * 100, 8) + "%" }}>
                    <span className="rp-funnel-ic"><Icon name={f.icon} size={14} /></span>
                    <span className="rp-funnel-v">{f.value.toLocaleString()}</span>
                  </div>
                  <span className="rp-funnel-lbl">{f.label}</span>
                </div>
                {i < funnel.length - 1 && (
                  <div className="rp-funnel-drop"><Icon name="arrow-down" size={12} /> {Math.round((funnel[i + 1].value / (f.value || 1)) * 100)}% continue</div>
                )}
              </div>
            ))}
            <div className="rp-funnel-rev"><Icon name="dollar-sign" size={14} /> Revenue generated <b>{rpFmtMoney(c.revenue)}</b></div>
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Campaign metrics</h3><span>Conversion &amp; engagement</span></div></div>
          <div className="rp-camp-metrics">
            <div className="rp-cm"><span>Nutrition engagement rate</span><b>{c.engRate}%</b></div>
            <div className="rp-cm"><span>View → order conversion</span><b>{c.convRate}%</b></div>
            <div className="rp-cm"><span>Revenue per view</span><b>${(c.revenue / (c.views || 1)).toFixed(2)}</b></div>
            <div className="rp-cm"><span>Avg order value</span><b>${(c.revenue / (c.orders || 1)).toFixed(2)}</b></div>
          </div>
          <div className="rp-camp-insight"><Icon name="lightbulb" size={13} /> {c.convRate >= 35 ? "Strong conversion, this health angle resonates. Consider extending the campaign." : "Customers engage with the nutrition info but convert below average, test pricing or positioning."}</div>
        </div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>All campaigns</h3><span>Funnel comparison</span></div></div>
        <table className="rp-table">
          <thead><tr><th>Campaign</th><th>Status</th><th>Views</th><th>Nutrition eng.</th><th>Orders</th><th>Conv.</th><th>Revenue</th></tr></thead>
          <tbody>
            {camps.map((cm, i) => (
              <tr key={cm.id} className="rp-tr-click" onClick={() => setSel(i)}>
                <td className="rp-td-nm">{cm.name}</td>
                <td><span className={`pill ${cm.status === "active" ? "success" : "neutral"}`} style={{ fontSize: 10 }}>{cm.status}</span></td>
                <td>{cm.views.toLocaleString()}</td>
                <td>{cm.nutritionEng.toLocaleString()}</td>
                <td>{cm.orders}</td>
                <td><span className={`rp-opp ${cm.convRate >= 35 ? "hi" : cm.convRate >= 25 ? "mid" : "lo"}`}>{cm.convRate}%</span></td>
                <td className="rp-td-rev">{rpFmtMoney(cm.revenue)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

/* ═══════════════════ Revenue Intelligence (PRD §11, Pro) ═══════════════════ */
function RpRevenue({ opts }) {
  const r = rptRevenueIntel(opts);
  const mixColors = ["#2f6b18", "#6938EF", "#B54708", "#157347", "#0E7490", "#9333EA"];
  return (
    <>
      <div className="rp-kpis">
        <RpKpi label="Revenue" value={rpFmtMoney(r.revenue)} icon="dollar-sign" tone="brand" />
        <RpKpi label="Gross profit" value={rpFmtMoney(r.profit)} icon="wallet" tone="green" />
        <RpKpi label="Margin" value={r.margin + "%"} icon="percent" tone="amber" />
        <RpKpi label="Healthy revenue" value={r.healthyPct + "%"} icon="leaf" tone="violet" />
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Healthy vs. unhealthy revenue</h3><span>Share of revenue by nutrition profile</span></div></div>
          <div className="rp-split">
            <div className="rp-split-bar">
              <span className="rp-split-h" style={{ width: r.healthyPct + "%" }} />
              <span className="rp-split-u" style={{ width: r.unhealthyPct + "%" }} />
            </div>
            <div className="rp-split-legend">
              <div><span className="rp-dot" style={{ background: "#2f6b18" }} /> Healthy <b>{r.healthyPct}%</b> · {rpFmtMoney(r.healthyRev)}</div>
              <div><span className="rp-dot" style={{ background: "var(--gray-400)" }} /> Other <b>{r.unhealthyPct}%</b> · {rpFmtMoney(r.unhealthyRev)}</div>
            </div>
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Nutrition revenue mix</h3><span>Revenue by health angle</span></div></div>
          <div className="rp-mix">
            <RpDonut data={r.mix.map((m, i) => ({ ...m, color: mixColors[i % mixColors.length] }))} />
            <div className="rp-mix-legend">
              {r.mix.map((m, i) => (
                <div key={m.label} className="rp-mix-row">
                  <span className="rp-dot" style={{ background: mixColors[i % mixColors.length] }} />
                  <span className="rp-mix-lbl">{m.label}</span>
                  <b>{m.pct}%</b>
                </div>
              ))}
              {r.mix.length === 0 && <div className="rp-chart-empty">No tagged revenue in this range.</div>}
            </div>
          </div>
        </div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Top revenue items</h3><span>Revenue · margin contribution</span></div></div>
        <table className="rp-table">
          <thead><tr><th>Item</th><th>Units</th><th>Revenue</th><th>Profit</th><th>Margin</th></tr></thead>
          <tbody>
            {r.topItems.map((it) => {
              const m = it.revenue ? Math.round((it.profit / it.revenue) * 100) : 0;
              return (
                <tr key={it.itemId}>
                  <td className="rp-td-nm">{it.name}</td>
                  <td>{it.units}</td>
                  <td className="rp-td-rev">{rpFmtMoney(it.revenue)}</td>
                  <td>{rpFmtMoney(it.profit)}</td>
                  <td><span className={`rp-opp ${m >= 65 ? "hi" : m >= 55 ? "mid" : "lo"}`}>{m}%</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

/* donut chart */
function RpDonut({ data }) {
  const total = data.reduce((a, b) => a + b.value, 0) || 1;
  const R = 54, sw = 22, C = 2 * Math.PI * R;
  let acc = 0;
  return (
    <svg viewBox="0 0 140 140" width="150" height="150" className="rp-donut">
      <circle cx="70" cy="70" r={R} fill="none" stroke="var(--gray-100)" strokeWidth={sw} />
      {data.map((d, i) => {
        const frac = d.value / total;
        const dash = `${frac * C} ${C}`;
        const off = -acc * C;
        acc += frac;
        return <circle key={i} cx="70" cy="70" r={R} fill="none" stroke={d.color} strokeWidth={sw} strokeDasharray={dash} strokeDashoffset={off} transform="rotate(-90 70 70)" />;
      })}
      <text x="70" y="66" textAnchor="middle" fontSize="11" fontWeight="600" fill="var(--gray-500)">Mix</text>
      <text x="70" y="82" textAnchor="middle" fontSize="15" fontWeight="800" fill="var(--gray-900)">{data.length}</text>
    </svg>
  );
}

/* ═══════════════════ Health Intelligence (PRD §6, Pro) ═══════════════════ */
function RpHealth({ opts }) {
  const interests = rptHealthInterest(opts);
  const trend = rptHealthTrend(opts);
  const eng = rptEngagementTotals(opts);
  const nutr = rptNutrition(opts);
  const items = rptEngagement(opts);
  // opportunity = high health interest but low orders
  const opps = items.slice().sort((a, b) => b.opportunity - a.opportunity).slice(0, 5);
  const topInterest = interests[0];
  const maxInterest = Math.max(...interests.map((i) => i.value), 1);
  const intColors = ["#2f6b18", "#6938EF", "#B54708", "#157347", "#0E7490", "#9333EA", "#BE123C"];

  return (
    <>
      <div className="rp-kpis">
        <RpKpi label="Health-tag views" value={rpFmtK(eng.healthTagViews)} icon="heart-pulse" tone="brand" />
        <RpKpi label="Top interest" value={topInterest ? topInterest.label : "—"} icon="award" tone="green" small />
        <RpKpi label="Healthy order share" value={nutr.healthyPct + "%"} icon="leaf" tone="amber" />
        <RpKpi label="Loraa health Qs" value={rpFmtK(eng.loraaQs)} icon="message-circle-question" tone="violet" />
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Health interest distribution</h3><span>What customers engage with</span></div></div>
          <div className="rp-hbars">
            {interests.map((it, i) => (
              <div key={it.label} className="rp-hbar-row">
                <span className="rp-hbar-lbl">{it.label}</span>
                <span className="rp-hbar-track"><i style={{ width: (it.value / maxInterest) * 100 + "%", background: intColors[i % intColors.length] }} /></span>
                <span className="rp-hbar-v">{it.pct}%</span>
              </div>
            ))}
            {interests.length === 0 && <div className="rp-chart-empty">No health-interest signals in this range.</div>}
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Health interest trend</h3><span>% of orders with a health tag · {opts.range}d</span></div></div>
          <RpAreaChart data={trend} xKey="date" yKey="value" />
        </div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Health opportunities</h3><span className="rp-gold"><Icon name="lightbulb" size={11} /> High interest · low orders</span></div></div>
        <table className="rp-table">
          <thead><tr><th>Item</th><th>Health-tag views</th><th>Loraa Qs</th><th>Orders</th><th>Opportunity</th></tr></thead>
          <tbody>
            {opps.map((it) => (
              <tr key={it.itemId}>
                <td className="rp-td-nm">{it.name}{(it.tags || []).slice(0, 1).map((t) => <span key={t} className="rp-chip-tag">{t}</span>)}</td>
                <td>{it.healthTagViews}</td>
                <td>{it.loraaQs}</td>
                <td>{it.orders}</td>
                <td><span className={`rp-opp ${it.opportunity >= 55 ? "hi" : it.opportunity >= 30 ? "mid" : "lo"}`}>{it.opportunity}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

/* ═══════════════════ Menu Performance (PRD §6, Pro; view-vs-order gap) ═══════════════════ */
function RpMenuPerf({ opts }) {
  const rows = rptMenuPerformance(opts);
  const score = rptMenuHealthScore(opts);
  const worst = rows.slice(0, 5); // biggest drop-off (rows already sorted by dropOff desc)
  const ai = rptAiInsights(opts);
  const scoreTone = score >= 75 ? "ok" : score >= 55 ? "mid" : "warn";
  return (
    <>
      <div className="rp-row rp-row-2">
        <div className="rp-card rp-mhs">
          <div className="rp-card-h"><div><h3>Menu health score</h3><span>Avg nutrition score across the menu</span></div></div>
          <div className="rp-mhs-body">
            <div className={`rp-mhs-ring ${scoreTone}`}>
              <svg viewBox="0 0 120 120" width="120" height="120">
                <circle cx="60" cy="60" r="50" fill="none" stroke="var(--gray-100)" strokeWidth="11" />
                <circle cx="60" cy="60" r="50" fill="none" strokeWidth="11" strokeLinecap="round"
                  strokeDasharray={2 * Math.PI * 50} strokeDashoffset={2 * Math.PI * 50 * (1 - score / 100)}
                  transform="rotate(-90 60 60)" className="rp-mhs-arc" />
                <text x="60" y="62" textAnchor="middle" dominantBaseline="middle" fontSize="28" fontWeight="800" fill="var(--gray-900)">{score}</text>
              </svg>
            </div>
            <p>{score >= 75 ? "Strong, most dishes score well on nutrition." : score >= 55 ? "Mixed, several dishes could be made healthier." : "At risk, many dishes score low on nutrition."}</p>
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>View → order drop-off</h3><span className="rp-gold"><Icon name="lightbulb" size={11} /> Biggest opportunity</span></div></div>
          <div className="rp-rank">
            {worst.map((it) => (
              <div key={it.itemId} className="rp-rank-row">
                <span className="rp-rank-nm">{it.name}</span>
                <span className="rp-gap"><span className="rp-gap-views">{it.views} views</span><Icon name="arrow-right" size={11} /><span className="rp-gap-orders">{it.orders} orders</span></span>
                <span className={`rp-rank-v ${it.conversion < 35 ? "rp-down" : ""}`}>{it.conversion}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Menu item grid</h3><span>Sales · nutrition score · performance</span></div></div>
        <table className="rp-table">
          <thead><tr><th>Item</th><th>Units</th><th>Revenue</th><th>Views</th><th>Conversion</th><th>Nutrition</th><th>Performance</th></tr></thead>
          <tbody>
            {rows.map((it) => {
              const perf = it.conversion >= 45 && it.nutritionScore >= 65 ? "strong" : it.conversion < 30 || it.nutritionScore < 45 ? "weak" : "ok";
              return (
                <tr key={it.itemId}>
                  <td className="rp-td-nm">{it.name}</td>
                  <td>{it.units}</td>
                  <td className="rp-td-rev">{rpFmtMoney(it.revenue)}</td>
                  <td>{it.views}</td>
                  <td>{it.conversion}%</td>
                  <td><span className={`rp-nscore ${it.nutritionScore >= 65 ? "ok" : it.nutritionScore >= 45 ? "mid" : "warn"}`}>{it.nutritionScore}</span></td>
                  <td style={{ textAlign: "right" }}><span className={`rp-perf ${perf}`}>{perf === "strong" ? "Strong" : perf === "weak" ? "Replace" : "OK"}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <RpAiPanel insights={ai} />
    </>
  );
}

/* ═══════════════════ Customer Trends (PRD §5, anonymous, Enterprise) ═══════════════════ */
function RpTrends({ opts }) {
  const c = rptCustomers(opts);
  const freq = rptVisitFrequency(opts);
  const maxFreq = Math.max(...freq.map((f) => f.n), 1);
  const dpMax = Math.max(...c.daypart.map((d) => d.value), 1);
  const ai = rptAiInsights(opts);
  return (
    <>
      <div className="rp-kpis">
        <RpKpi label="Unique guests" value={c.uniqueIds.toLocaleString()} icon="users" tone="violet" />
        <RpKpi label="Returning" value={c.returningPct + "%"} icon="repeat" tone="brand" />
        <RpKpi label="Avg orders / guest" value={c.avgOrders} icon="receipt" tone="amber" />
        <RpKpi label="Anonymous IDs" value="100%" icon="shield-check" tone="green" small />
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Visit frequency</h3><span>Guests by number of visits</span></div></div>
          <div className="rp-freq">
            {freq.map((f) => (
              <div key={f.label} className="rp-freq-col">
                <div className="rp-freq-bar"><i style={{ height: (f.n / maxFreq) * 100 + "%" }} /><span className="rp-freq-v">{f.n}</span></div>
                <span className="rp-freq-lbl">{f.label}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Meal-time preferences</h3><span>Orders by daypart</span></div></div>
          <div className="rp-rank">
            {c.daypart.map((d) => (
              <div key={d.label} className="rp-rank-row">
                <span className="rp-rank-nm">{d.label}</span>
                <span className="rp-rank-bar"><i style={{ width: (d.value / dpMax) * 100 + "%" }} /></span>
                <span className="rp-rank-v">{d.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Preference clusters</h3><span>Guests grouped by their top health tag</span></div></div>
          <div className="rp-clusters">
            {c.clusters.map((cl, i) => (
              <div key={cl.label} className="rp-cluster" style={{ borderColor: rpCatColor(i) + "55" }}>
                <span className="rp-cluster-dot" style={{ background: rpCatColor(i) }} />
                <span className="rp-cluster-nm">{cl.label}</span>
                <b className="rp-cluster-v">{cl.value}</b>
              </div>
            ))}
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Anonymous guest sample</h3><span>Behavioral data only, no identity stored</span></div></div>
          <table className="rp-table">
            <thead><tr><th>Anonymous ID</th><th>Orders</th><th>Top preference</th></tr></thead>
            <tbody>
              {c.sample.map((u) => (
                <tr key={u.id}>
                  <td className="rp-td-nm rp-mono">{u.id}</td>
                  <td>{u.orders}</td>
                  <td style={{ textAlign: "right" }}>{u.top !== "—" ? <span className="rp-chiptag">{u.top}</span> : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <RpAiPanel insights={ai} />
    </>
  );
}

/* ═══════════════════ Nutrition Insights (PRD §4, Pro differentiator) ═══════════════════ */
function RpNutrition({ opts }) {
  const [basis, setBasis] = useRpState("order");
  const n = rptNutrition(opts);
  const cust = rptCustomers(opts);
  const kpiScale = basis === "day" ? Math.max(1, Math.round((rptFilter(opts).length) / (opts.range || 30))) : basis === "session" ? Number(cust.avgOrders) || 1 : 1;
  const ing = rptIngredientUsage(opts);
  const dishes = rptTopDishes(opts);
  const scl = (v) => Math.round(v * kpiScale);
  const basisLabel = basis === "order" ? "per order" : basis === "session" ? "per customer session" : "per day";

  return (
    <>
      <div className="rp-card rp-basis">
        <span>Showing nutrition <b>{basisLabel}</b></span>
        <div className="rp-seg sm">
          {[{ v: "order", l: "Per order" }, { v: "session", l: "Per session" }, { v: "day", l: "Per day" }].map((b) => (
            <button key={b.v} className={basis === b.v ? "on" : ""} onClick={() => setBasis(b.v)}>{b.l}</button>
          ))}
        </div>
      </div>

      <div className="rp-kpis">
        <RpKpi label="Avg calories" value={scl(n.avgCalories).toLocaleString() + " kcal"} icon="flame" tone="amber" />
        <RpKpi label="Avg protein" value={scl(n.avgProtein) + " g"} icon="drumstick" tone="brand" />
        <RpKpi label="Avg carbs" value={scl(n.avgCarbs) + " g"} icon="wheat" tone="violet" />
        <RpKpi label="Avg fat" value={scl(n.avgFat) + " g"} icon="droplet" tone="green" />
      </div>

      <div className="rp-card">
        <div className="rp-card-h">
          <div><h3>Nutrient consumption trend</h3><span>Avg sodium &amp; sugar {basisLabel} · last {opts.range} days</span></div>
          <div className="rp-legend"><span><i className="rp-dot" style={{ background: "#e5484d" }} /> Sodium (mg)</span><span><i className="rp-dot" style={{ background: "#d99404" }} /> Sugar (g)</span></div>
        </div>
        <RpDualLine data={n.trend} aKey="sodium" bKey="sugar" aColor="#e5484d" bColor="#d99404" />
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Health tag distribution</h3><span>Share of orders carrying each tag</span></div></div>
          <div className="rp-rank">
            {n.tags.slice(0, 6).map((t) => {
              const healthy = /protein|fiber|low-carb|vegan|gluten|heart|diabet/i.test(t.label);
              return (
                <div key={t.label} className="rp-rank-row">
                  <span className="rp-rank-nm">{t.label}</span>
                  <span className="rp-rank-bar"><i style={{ width: t.pct + "%", background: healthy ? "linear-gradient(90deg,#6aa84f,#2f6b18)" : "linear-gradient(90deg,#f0a868,#d99404)" }} /></span>
                  <span className="rp-rank-v">{t.pct}%</span>
                </div>
              );
            })}
          </div>
          <div className={`rp-sodium ${n.healthyPct >= 45 ? "ok" : "warn"}`} style={{ marginTop: 12 }}>
            <Icon name={n.healthyPct >= 45 ? "leaf" : "alert-triangle"} size={13} /> {n.healthyPct}% of orders carry a health tag {n.healthyPct >= 45 ? ", strong better-for-you demand" : ", room to grow healthier options"}
          </div>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Most consumed ingredients</h3><span>By units sold</span></div></div>
          <div className="rp-rank">
            {ing.map((it, i) => (
              <div key={it.label} className="rp-rank-row">
                <span className="rp-rank-n">{i + 1}</span>
                <span className="rp-rank-nm">{it.label}</span>
                <span className="rp-rank-bar"><i style={{ width: (it.units / (ing[0].units || 1)) * 100 + "%" }} /></span>
                <span className="rp-rank-v">{it.units}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Top consumed dishes</h3><span>By units, what people actually eat</span></div></div>
        <table className="rp-table">
          <thead><tr><th>Dish</th><th>Units</th><th>Calories</th><th>Health tags</th></tr></thead>
          <tbody>
            {dishes.map((d) => (
              <tr key={d.itemId}>
                <td className="rp-td-nm">{d.name}</td>
                <td>{d.units}</td>
                <td>{d.calories} kcal</td>
                <td style={{ textAlign: "right" }}>{(d.tags || []).slice(0, 2).map((t) => <span key={t} className="rp-chiptag">{t}</span>)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <RpAiPanel insights={rptAiInsights(opts)} />
    </>
  );
}

/* dual-line SVG chart (sodium + sugar, independently scaled) */
function RpDualLine({ data, aKey, bKey, aColor, bColor }) {
  if (!data || data.length < 2) return <div className="rp-chart-empty">Not enough data for this range.</div>;
  const W = 720, H = 200, P = 30;
  const aMax = Math.max(...data.map((d) => d[aKey])) * 1.15 || 1;
  const bMax = Math.max(...data.map((d) => d[bKey])) * 1.15 || 1;
  const x = (i) => P + (i / (data.length - 1)) * (W - P * 2);
  const yA = (v) => H - P - (v / aMax) * (H - P * 2);
  const yB = (v) => H - P - (v / bMax) * (H - P * 2);
  const path = (key, yf) => data.map((d, i) => `${i === 0 ? "M" : "L"}${x(i).toFixed(1)},${yf(d[key]).toFixed(1)}`).join(" ");
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="rp-chart" preserveAspectRatio="none">
      {[0, 0.25, 0.5, 0.75, 1].map((t, i) => <line key={i} x1={P} x2={W - P} y1={P + t * (H - P * 2)} y2={P + t * (H - P * 2)} stroke="var(--gray-100)" strokeWidth="1" />)}
      <path d={path(aKey, yA)} fill="none" stroke={aColor} strokeWidth="2.5" strokeLinejoin="round" />
      <path d={path(bKey, yB)} fill="none" stroke={bColor} strokeWidth="2.5" strokeLinejoin="round" />
    </svg>
  );
}

/* ═══════════════════ Sales Report (PRD §3) ═══════════════════ */
function RpSales({ opts }) {
  const [grain, setGrain] = useRpState("daily");
  const [detail, setDetail] = useRpState(null);
  const kpis = rptKpis(opts);
  const rev = rptRevenueBy(grain, opts);
  const items = rptByItem(opts).map((it) => ({ ...it, trend: rptItemTrend(it.itemId, opts) }));
  const top = items.slice(0, 8);
  const low = items.slice(-4).reverse();
  const cats = rptCategorySplit(opts);
  const catTotal = cats.reduce((a, b) => a + b.value, 0) || 1;

  return (
    <>
      <div className="rp-kpis">
        <RpKpi label="Total revenue" value={rpFmtMoney(kpis.revenue)} icon="dollar-sign" tone="brand" trend={kpis.growth} trendLabel="vs prev." />
        <RpKpi label="Orders" value={kpis.orders.toLocaleString()} icon="receipt" tone="violet" />
        <RpKpi label="Avg order value" value={"$" + kpis.aov.toFixed(2)} icon="trending-up" tone="amber" />
        <RpKpi label="Profit margin" value={kpis.margin.toFixed(0) + "%"} icon="percent" tone="green" />
      </div>

      <div className="rp-card">
        <div className="rp-card-h">
          <div><h3>Revenue</h3><span>{grain === "hourly" ? "By hour of day" : grain === "weekly" ? "By week" : "Daily"} · {opts.range}-day window</span></div>
          <div className="rp-seg sm">
            {[{ v: "hourly", l: "Hourly" }, { v: "daily", l: "Daily" }, { v: "weekly", l: "Weekly" }].map((g) => (
              <button key={g.v} className={grain === g.v ? "on" : ""} onClick={() => setGrain(g.v)}>{g.l}</button>
            ))}
          </div>
        </div>
        <RpBarChart data={rev} />
      </div>

      <div className="rp-row rp-row-2">
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Top selling items</h3><span>Click a row for item detail</span></div></div>
          <table className="rp-table">
            <thead><tr><th>Item</th><th>Orders</th><th>Revenue</th><th>Trend</th></tr></thead>
            <tbody>
              {top.map((it) => (
                <tr key={it.itemId} onClick={() => setDetail(it.itemId)} className="rp-tr-click">
                  <td className="rp-td-nm">{it.name}</td>
                  <td>{it.orders}</td>
                  <td className="rp-td-rev">{rpFmtMoney(it.revenue)}</td>
                  <td><span className={`rp-trend ${it.trend >= 0 ? "up" : "down"}`}><Icon name={it.trend >= 0 ? "arrow-up-right" : "arrow-down-right"} size={12} stroke={2.6} />{Math.abs(it.trend)}%</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="rp-card">
          <div className="rp-card-h"><div><h3>Low performing</h3><span>Bottom by revenue</span></div></div>
          <table className="rp-table">
            <thead><tr><th>Item</th><th>Orders</th><th>Revenue</th></tr></thead>
            <tbody>
              {low.map((it) => (
                <tr key={it.itemId} onClick={() => setDetail(it.itemId)} className="rp-tr-click">
                  <td className="rp-td-nm">{it.name}</td>
                  <td>{it.orders}</td>
                  <td className="rp-td-rev dim">{rpFmtMoney(it.revenue)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="rp-card">
        <div className="rp-card-h"><div><h3>Category breakdown</h3><span>Revenue share by menu category</span></div></div>
        <div className="rp-catbars">
          {cats.map((c, i) => (
            <div key={c.label} className="rp-catbar">
              <div className="rp-catbar-top"><span>{c.label}</span><b>{rpFmtMoney(c.value)} · {Math.round((c.value / catTotal) * 100)}%</b></div>
              <div className="rp-catbar-track"><i style={{ width: (c.value / cats[0].value) * 100 + "%", background: rpCatColor(i) }} /></div>
            </div>
          ))}
        </div>
      </div>

      {detail && <RpItemDetail itemId={detail} opts={opts} onClose={() => setDetail(null)} />}
    </>
  );
}
function rpCatColor(i) { return ["#2f6b18", "#6938EF", "#B54708", "#157347", "#2A54E5", "#9333ea"][i % 6]; }

/* Item drill-down (slide panel) */
function RpItemDetail({ itemId, opts, onClose }) {
  const d = rptItemDetail(itemId, opts);
  if (!d) return null;
  const maxTod = Math.max(...d.timeOfDay.map((t) => t.value), 1);
  return (
    <div className="of-panel-scrim" onClick={onClose}>
      <div className="of-panel" onClick={(e) => e.stopPropagation()}>
        <div className="of-panel-h">
          <div><div className="of-panel-t">{d.item.name}</div><div className="of-panel-sub">{d.item.cuisine} · {d.item.category} · ${d.item.price.toFixed(2)}</div></div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="of-panel-body">
          <div className="rp-id-kpis">
            <div><span>Revenue</span><b>{rpFmtMoney(d.revenue)}</b></div>
            <div><span>Orders</span><b>{d.orders}</b></div>
            <div><span>Conversion</span><b>{d.conversion}%</b></div>
            <div><span>Trend</span><b className={d.trendPct >= 0 ? "rp-up" : "rp-down"}>{d.trendPct >= 0 ? "+" : ""}{d.trendPct}%</b></div>
          </div>
          <div className="rp-id-sec">Sales trend</div>
          <RpAreaChart data={d.trend} xKey="date" yKey="revenue" />
          <div className="rp-id-sec">Time of day</div>
          <div className="rp-tod">
            {d.timeOfDay.map((t) => (
              <div key={t.label} className="rp-tod-row"><span>{t.label}</span><div className="rp-tod-track"><i style={{ width: (t.value / maxTod) * 100 + "%" }} /></div><b>{t.value}</b></div>
            ))}
          </div>
          <div className="rp-id-sec">Frequently bought with</div>
          <div className="rp-pairs">
            {d.pairings.length ? d.pairings.map((p) => <div key={p.name} className="rp-pair"><Icon name="link" size={12} /> {p.name} <span>×{p.count}</span></div>) : <div className="rp-chart-empty" style={{ padding: "12px 0" }}>No strong pairings yet.</div>}
          </div>
          <div className="rp-id-ai">
            <div className="rp-id-ai-h"><span className="rp-ai-spark"><Icon name="lightbulb" size={13} /></span> Suggested actions</div>
            {d.actions.map((a, i) => <div key={i} className="rp-id-ai-row"><Icon name="circle-dot" size={12} /> {a}</div>)}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ───────── SVG bar chart ───────── */
function RpBarChart({ data }) {
  if (!data || !data.length) return <div className="rp-chart-empty">No data for this range.</div>;
  const W = 720, H = 200, P = 28;
  const max = Math.max(...data.map((d) => d.revenue)) * 1.1 || 1;
  const n = data.length;
  const gap = 4, bw = (W - P * 2) / n - gap;
  const y = (v) => H - P - (v / max) * (H - P * 2);
  const everyX = Math.ceil(n / 12);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="rp-chart" preserveAspectRatio="none">
      {[0, 0.25, 0.5, 0.75, 1].map((t, i) => <line key={i} x1={P} x2={W - P} y1={P + t * (H - P * 2)} y2={P + t * (H - P * 2)} stroke="var(--gray-100)" strokeWidth="1" />)}
      {data.map((d, i) => {
        const x = P + i * (bw + gap);
        return <rect key={i} x={x} y={y(d.revenue)} width={bw} height={Math.max(0, H - P - y(d.revenue))} rx="2.5" fill="var(--green-700, #2f6b18)" opacity={0.55 + 0.45 * (d.revenue / max)} />;
      })}
      {data.map((d, i) => i % everyX === 0 ? <text key={i} x={P + i * (bw + gap) + bw / 2} y={H - 8} textAnchor="middle" fontSize="9" fill="var(--gray-400)">{d.label}</text> : null)}
    </svg>
  );
}

/* ───────── SVG area chart ───────── */
function RpAreaChart({ data, xKey, yKey }) {
  if (!data || data.length < 2) return <div className="rp-chart-empty">Not enough data for this range.</div>;
  const W = 720, H = 220, P = 28;
  const vals = data.map((d) => d[yKey]);
  const max = Math.max(...vals) * 1.1 || 1;
  const x = (i) => P + (i / (data.length - 1)) * (W - P * 2);
  const y = (v) => H - P - (v / max) * (H - P * 2);
  const line = data.map((d, i) => `${i === 0 ? "M" : "L"}${x(i).toFixed(1)},${y(d[yKey]).toFixed(1)}`).join(" ");
  const area = `${line} L${x(data.length - 1).toFixed(1)},${H - P} L${x(0).toFixed(1)},${H - P} Z`;
  const ticks = [0, 0.25, 0.5, 0.75, 1];
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="rp-chart" preserveAspectRatio="none">
      <defs>
        <linearGradient id="rpArea" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="var(--green-700, #2f6b18)" stopOpacity=".26" />
          <stop offset="100%" stopColor="var(--green-700, #2f6b18)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {ticks.map((t, i) => <line key={i} x1={P} x2={W - P} y1={P + t * (H - P * 2)} y2={P + t * (H - P * 2)} stroke="var(--gray-100)" strokeWidth="1" />)}
      <path d={area} fill="url(#rpArea)" />
      <path d={line} fill="none" stroke="var(--green-700, #2f6b18)" strokeWidth="2.5" strokeLinejoin="round" />
      {data.map((d, i) => (i % Math.ceil(data.length / 8) === 0) ? <circle key={i} cx={x(i)} cy={y(d[yKey])} r="3" fill="#fff" stroke="var(--green-700, #2f6b18)" strokeWidth="2" /> : null)}
    </svg>
  );
}

if (typeof window !== "undefined") Object.assign(window, { ReportsModule, RpAiPanel, RpAreaChart, RpKpi, RpSales, RpBarChart, RpItemDetail, RpNutrition, RpDualLine, RpTrends, RpMenuPerf, RpHealth, RpRevenue, RpDonut, RpCampaign, RpForecast, RpForecastChart, RpBenchmark, RpAdvisor, RpExec, RpPersonalized, RpAiFull, RpExports });
