// Modules — Today's Revenue breakdown, Top Services, Top Products, Marketing

// Donut for revenue breakdown
const Donut = ({ data, total, size = 160, thickness = 28, centerLabel = 'Today' }) => {
  const r = (size - thickness) / 2;
  const cx = size / 2, cy = size / 2;
  const C = 2 * Math.PI * r;
  let acc = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display:'block' }}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#F1F5F9" strokeWidth={thickness}/>
      {data.map(d => {
        const len = (d.value/total) * C;
        const off = C - acc;
        acc += len;
        return <circle key={d.name} cx={cx} cy={cy} r={r} fill="none" stroke={d.color} strokeWidth={thickness}
                       strokeDasharray={`${len} ${C-len}`} strokeDashoffset={off}
                       transform={`rotate(-90 ${cx} ${cy})`} strokeLinecap="butt"/>;
      })}
      <text x={cx} y={cy - 4} textAnchor="middle" fontSize="11" fill="#94A3B8">{centerLabel}</text>
      <text x={cx} y={cy + 14} textAnchor="middle" fontSize="18" fontWeight="700" fill="#0F172A">{fmtMoney(total)}</text>
    </svg>
  );
};

const PERIOD_LABEL = { T: 'Today', WTD: 'Week to date', MTD: 'Month to date', QTD: 'Quarter to date', YTD: 'Year to date' };
const PERIOD_SHORT = { T: 'Today', WTD: 'WTD', MTD: 'MTD', QTD: 'QTD', YTD: 'YTD' };

const RevenueBreakdown = ({ data }) => {
  const [period, setPeriod] = React.useState('T');
  const mult = window.FRANCHISE_DATA.PERIOD_MULT[period];
  // scale & jitter slightly per segment so totals match the period KPI feel without being identical to T×mult
  const scaled = data.map((d, i) => {
    const jitter = [1.00, 0.98, 1.04, 0.92][i % 4];
    return { ...d, value: Math.round(d.value * mult * jitter) };
  });
  const total = scaled.reduce((a, b) => a + b.value, 0);
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="dollar" size={16} stroke={2}/>
          <h2>Revenue Breakdown — {PERIOD_SHORT[period]}</h2>
          <InfoDot tip="How net sales split across services, retail products, tips, and gift cards across the network for the selected period."/>
        </div>
        <PeriodPicker value={period} onChange={setPeriod}/>
      </header>
      <div className="rev-break">
        <Donut data={scaled} total={total} centerLabel={PERIOD_LABEL[period]}/>
        <ul className="rev-break-list">
          {scaled.map(d => (
            <li key={d.name}>
              <span className="rev-dot" style={{ background: d.color }}/>
              <div className="rev-name">{d.name}</div>
              <div className="rev-val">{fmtMoney(d.value)}</div>
              <div className="rev-pct">{((d.value/total)*100).toFixed(0)}%</div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
};

// Bar list (services & products)
const BarList = ({ items, valueKey, max, palette }) => (
  <ul className="bar-list">
    {items.map((it, i) => (
      <li key={it.name + i}>
        <div className="bar-list-head">
          <div>
            <div className="bar-list-name">{it.name}</div>
            <div className="bar-list-sub">{it.sub}</div>
          </div>
          <div className="bar-list-val">{fmtMoney(it[valueKey])}</div>
        </div>
        <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: (it[valueKey]/max*100).toFixed(1)+'%', background: it.color || palette[i % palette.length] }}/></div>
      </li>
    ))}
  </ul>
);

const TopServicesCard = () => {
  const [period, setPeriod] = React.useState('T');
  const services = window.FRANCHISE_DATA.TOP_SERVICES;
  const items = services.map(s => ({ ...s, sub: `${s.share}% of revenue · ${s.yoy >= 0 ? '+' : ''}${s.yoy}% YoY` }));
  const max = Math.max(...items.map(s => s.revenue));
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="scissors" size={16} stroke={2}/>
          <h2>Top Services — Network</h2>
          <InfoDot tip="Services ranked by gross revenue across all 10 locations for the selected period."/>
        </div>
        <PeriodPicker value={period} onChange={setPeriod}/>
      </header>
      <BarList items={items} valueKey="revenue" max={max}/>
    </section>
  );
};

const TopProductsCard = () => {
  const [period, setPeriod] = React.useState('T');
  const products = window.FRANCHISE_DATA.TOP_PRODUCTS;
  const items = products.map(p => ({
    ...p,
    sub: <span>{p.sku} · {p.units} units · {p.yoy >= 0 ? '+' : ''}{p.yoy}% YoY {p.stock !== 'healthy' && <span className={'stock-pill stock-' + p.stock}>{p.stock}</span>}</span>,
  }));
  const max = Math.max(...items.map(p => p.revenue));
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="box" size={16} stroke={2}/>
          <h2>Top Products — Network</h2>
          <InfoDot tip="Retail products ranked by revenue across all 10 locations. Low/critical stock pills surface reorder needs."/>
        </div>
        <PeriodPicker value={period} onChange={setPeriod}/>
      </header>
      <BarList items={items} valueKey="revenue" max={max}/>
    </section>
  );
};

// Marketing — only channels we offer
const Marketing = ({ campaigns }) => {
  const [period, setPeriod] = React.useState('MTD');
  const totalSpend = campaigns.reduce((a,c) => a + c.spend, 0);
  const totalRev = campaigns.reduce((a,c) => a + c.revenue, 0);
  const blendedRoas = totalRev / totalSpend;
  const CC = window.FRANCHISE_DATA.CHANNEL_COLORS;
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="megaphone" size={16} stroke={2}/>
          <h2>Marketing Performance</h2>
          <InfoDot tip="Performance across the channels we offer: Email, SMS, In-app, Referral, Reward, and Loyalty. ROAS = Return on Ad Spend (revenue ÷ spend)."/>
        </div>
        <div style={{ display:'flex', gap: 10, alignItems:'center' }}>
          <div className="mk-blended">
            <span>Blended ROAS</span>
            <b>{blendedRoas.toFixed(1)}×</b>
          </div>
          <PeriodPicker value={period} onChange={setPeriod}/>
        </div>
      </header>
      <table className="mk-table">
        <thead><tr>
          <th>Campaign</th><th>Channel</th>
          <th className="num">Sent</th><th className="num">Opened</th><th className="num">Clicked</th>
          <th className="num">Spend</th><th className="num">Revenue</th><th className="num">ROAS</th><th>Status</th>
        </tr></thead>
        <tbody>
          {campaigns.map(c => (
            <tr key={c.name}>
              <td className="strong">{c.name}</td>
              <td><span className="channel-pill" style={{ background: CC[c.channel] + '22', color: CC[c.channel] }}>{c.channel}</span></td>
              <td className="num">{c.sent.toLocaleString()}</td>
              <td className="num">{c.opened.toLocaleString()} <span className="muted">({((c.opened/c.sent)*100).toFixed(0)}%)</span></td>
              <td className="num">{c.clicked.toLocaleString()} <span className="muted">({((c.clicked/c.sent)*100).toFixed(0)}%)</span></td>
              <td className="num">{fmtMoney(c.spend)}</td>
              <td className="num">{fmtMoney(c.revenue)}</td>
              <td className="num"><span className={'roas-chip ' + (c.roas >= 5 ? 'good' : c.roas >= 3 ? 'mid' : 'low')}>{c.roas.toFixed(1)}×</span></td>
              <td><span className="pill pill-live"><span className="pill-dot" style={{ background:'#22C55E' }}/>{c.status}</span></td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
};

Object.assign(window, { RevenueBreakdown, TopServicesCard, TopProductsCard, Marketing });
