// Alert cards row — system-grounded only

const ALERT_STYLES = {
  casl:      { bg:'#FEF2F2', border:'#FCA5A5', icon:'warn',     iconBg:'#FEE2E2', iconColor:'#DC2626', tagBg:'#FEE2E2', tagColor:'#B91C1C', tagLabel:'critical' },
  royalty:   { bg:'#FFFBEB', border:'#FCD34D', icon:'dollar',   iconBg:'#FEF3C7', iconColor:'#B45309', tagBg:'#FEF3C7', tagColor:'#92400E', tagLabel:'royalty' },
  nps:       { bg:'#FDF2F8', border:'#F9A8D4', icon:'star',     iconBg:'#FCE7F3', iconColor:'#DB2777', tagBg:'#FCE7F3', tagColor:'#9D174D', tagLabel:'reputation' },
  vendor:    { bg:'#FFF3E8', border:'#FDBA74', icon:'box',      iconBg:'#FFEDD5', iconColor:'#EA580C', tagBg:'#FFEDD5', tagColor:'#C2410C', tagLabel:'supply' },
  underperf: { bg:'#EEF2FF', border:'#A5B4FC', icon:'trend',    iconBg:'#E0E7FF', iconColor:'#4F46E5', tagBg:'#E0E7FF', tagColor:'#3730A3', tagLabel:'watch' },
};

const AlertCard = ({ a, onClick }) => {
  const s = ALERT_STYLES[a.kind];
  return (
    <article
      className={'alert-card' + (a.severity === 'critical' ? ' is-critical' : '') + (onClick ? ' is-clickable' : '')}
      style={{ background: s.bg, borderColor: s.border }}
      onClick={onClick}
      role={onClick ? 'button' : undefined}
      tabIndex={onClick ? 0 : undefined}
    >
      {a.severity === 'critical' && <div className="alert-card-banner">CRITICAL</div>}
      <div className="alert-card-top">
        <div className="alert-card-icon" style={{ background: s.iconBg, color: s.iconColor }}>
          <Icon name={s.icon} size={20} stroke={2} />
        </div>
        <div className="alert-card-tag" style={{ background: s.tagBg, color: s.tagColor }}>
          <span className="alert-card-count">{a.count}</span>
          <span>{s.tagLabel}</span>
        </div>
      </div>
      <div className="alert-card-title">{a.title}</div>
      <div className="alert-card-detail">{a.detail}</div>
      <button className="alert-card-cta" style={{ color: s.iconColor }} data-live={onClick ? '1' : undefined} onClick={(e) => { if (onClick) { e.stopPropagation(); onClick(); } }}>{a.cta} <Icon name="arrow-right" size={13} stroke={2.2}/></button>
    </article>
  );
};

const AlertRow = ({ alerts, onOpenCasl }) => (
  <section className="alerts-row">{alerts.map(a => <AlertCard key={a.kind} a={a} onClick={a.kind === 'casl' && onOpenCasl ? onOpenCasl : undefined}/>)}</section>
);

// ── Sparkline ───────────────────────────────────────────────────────
const Sparkline = ({ data, color, height = 28, width = 96 }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const span = max - min || 1;
  const step = width / (data.length - 1);
  const pts = data.map((v, i) => `${(i*step).toFixed(1)},${(height - ((v - min)/span)*height).toFixed(1)}`).join(' ');
  const fillPts = `0,${height} ${pts} ${width},${height}`;
  return (
    <svg width={width} height={height} style={{ display:'block' }} viewBox={`0 0 ${width} ${height}`}>
      <polygon points={fillPts} fill={color} fillOpacity="0.12" />
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

const Compliance = ({ level, flags }) => {
  const map = { green: { color:'#16A34A', bg:'#DCFCE7', label:'Compliant' },
                amber: { color:'#B45309', bg:'#FEF3C7', label:'Watch' },
                red:   { color:'#B91C1C', bg:'#FEE2E2', label:'Flagged' } };
  const c = map[level];
  return (
    <div style={{ display:'flex', gap: 4, alignItems:'center', flexWrap:'wrap' }}>
      <span className="pill" style={{ color: c.color, background: c.bg }}><span className="pill-dot" style={{ background: c.color }}/>{c.label}</span>
      {flags && flags.map(f => <span key={f} className="pill pill-flag" title={f === 'CASL' ? 'CASL violation' : 'PIPEDA flag'}>{f}</span>)}
    </div>
  );
};

const TypeBadge = ({ type }) => (
  <span className={'type-badge type-' + type}>{type}</span>
);

// ── Date range selector (small) ─────────────────────────────────────
const PeriodPicker = ({ value, onChange }) => (
  <div className="seg-group small">
    {[['T','T'],['WTD','WTD'],['MTD','MTD'],['QTD','QTD'],['YTD','YTD']].map(([k,lbl]) => (
      <button key={k} className={'seg' + (value === k ? ' is-on' : '')} onClick={() => onChange(k)}>{lbl}</button>
    ))}
  </div>
);

// ── Locations Leaderboard with field selector ───────────────────────
const FIELD_DEFS = {
  revenue:            { label:'Revenue',           num:true,  fmt: v => fmtMoneyFull(v), info:'Net sales at this shop for the period.' },
  utilization:        { label:'Utilization',       num:true,  fmt: v => v.toFixed(1) + '%', bar:true, info:'Booked ÷ available chair-hours.' },
  revPerHour:         { label:'Rev / Hour',        num:true,  fmt: v => '$' + v.toFixed(2), info:'Service revenue per booked chair-hour.' },
  nps:                { label:'NPS',               num:true,  fmt: v => v.toString(), chip:'nps', info:'Net Promoter Score from post-visit surveys.' },
  royalties:          { label:'Royalty (proj.)',  num:true,  fmt: v => '~' + fmtMoneyFull(v), info:'Projected royalty for this shop — modeled from net sales × the shop’s franchise agreement rate. Estimate only; not collected royalty.' },
  retention:          { label:'Retention',         num:true,  fmt: v => v + '%', info:'% of customers who returned within 90 days.' },
  loyaltyPenetration: { label:'Loyalty %',         num:true,  fmt: v => v + '%', info:'Share of customers who are active loyalty members.' },
  referrals:          { label:'Referrals',         num:true,  fmt: v => v.toString(), info:'Successful referrals via Refer-a-Friend program.' },
  redemptions:        { label:'Redemptions',       num:true,  fmt: v => v.toString(), info:'Loyalty rewards redeemed during the period.' },
  engagement:         { label:'Engagement',        num:true,  fmt: v => v + '%', info:'% of customers who opened, clicked, or replied to a campaign.' },
  casl:               { label:'CASL %',            num:true,  fmt: v => v + '%', chip:'compliance', info:'% of email sends to opted-in customers. <100% = potential CASL violation.' },
  pipeda:             { label:'PIPEDA %',          num:true,  fmt: v => v + '%', chip:'compliance', info:'% of customer data handling matching PIPEDA privacy standards.' },
};

const FIELD_PRESETS = {
  performance: ['revenue', 'utilization', 'revPerHour', 'nps', 'royalties'],
  compliance:  ['casl', 'pipeda', 'royalties', 'nps'],
  loyalty:     ['loyaltyPenetration', 'redemptions', 'referrals', 'retention', 'engagement'],
  engagement:  ['engagement', 'retention', 'referrals', 'nps', 'loyaltyPenetration'],
};

const FieldCell = ({ field, value }) => {
  const def = FIELD_DEFS[field];
  if (def.chip === 'nps') {
    return <span className={'nps-chip ' + (value >= 70 ? 'good' : value >= 60 ? 'mid' : 'low')}>{value}</span>;
  }
  if (def.chip === 'compliance') {
    const cls = value >= 95 ? 'good' : value >= 85 ? 'mid' : 'low';
    return <span className={'nps-chip ' + cls}>{value}%</span>;
  }
  if (def.bar) {
    return (
      <div className="util-wrap">
        <div className="util-bar"><div className="util-fill" style={{ width: value + '%', background: value >= 75 ? '#16A34A' : value >= 60 ? '#F59E0B' : '#EF4444' }}/></div>
        <span>{def.fmt(value)}</span>
      </div>
    );
  }
  return def.fmt(value);
};

const Leaderboard = ({ locations, onOpen, locationFilter }) => {
  const [sort, setSort] = React.useState({ key: 'revenue', dir: 'desc' });
  const [filter, setFilter] = React.useState('all');
  const [period, setPeriod] = React.useState('T');
  const [preset, setPreset] = React.useState('performance');
  const [fieldPickerOpen, setFieldPickerOpen] = React.useState(false);
  const [fields, setFields] = React.useState(FIELD_PRESETS.performance);

  const applyPreset = (p) => { setPreset(p); setFields(FIELD_PRESETS[p]); };
  const toggleField = (f) => {
    setPreset('custom');
    setFields(fs => fs.includes(f) ? fs.filter(x => x !== f) : fs.length < 6 ? [...fs, f] : fs);
  };

  const onSort = (key) => setSort(s => s.key === key ? { key, dir: s.dir === 'desc' ? 'asc' : 'desc' } : { key, dir: 'desc' });

  const rows = React.useMemo(() => {
    let r = locations.slice();
    if (locationFilter && locationFilter !== 'all') r = r.filter(l => l.id === locationFilter);
    if (filter === 'top')        r = r.slice().sort((a,b) => b.sssYoY - a.sssYoY).slice(0, 5);
    else if (filter === 'watch') r = r.filter(l => l.compliance === 'amber');
    else if (filter === 'risk')  r = r.filter(l => l.compliance === 'red' || l.sssYoY < 0);
    else if (filter === 'corporate')  r = r.filter(l => l.type === 'corporate');
    else if (filter === 'franchised') r = r.filter(l => l.type === 'franchised');

    return r.sort((a, b) => {
      const av = a[sort.key], bv = b[sort.key];
      if (typeof av === 'number') return sort.dir === 'desc' ? bv - av : av - bv;
      return sort.dir === 'desc' ? String(bv).localeCompare(String(av)) : String(av).localeCompare(String(bv));
    });
  }, [locations, sort, filter, locationFilter]);

  return (
    <section className="card leaderboard">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="building" size={16} stroke={2} />
          <h2>Locations Leaderboard</h2>
          <InfoDot tip="Every shop in the network ranked by your sorted column. Pick a field preset or build a custom view. Click any row to drill into that shop."/>
          <span className="card-head-count">{rows.length} of {locations.length}</span>
        </div>
        <div className="card-head-right">
          <PeriodPicker value={period} onChange={setPeriod}/>
          <div className="seg-group small">
            {[['all','All'],['corporate','Corp'],['franchised','Franchised'],['watch','Watch'],['risk','Risk']].map(([k,lbl]) => (
              <button key={k} className={'seg' + (filter === k ? ' is-on' : '')} onClick={() => setFilter(k)}>{lbl}</button>
            ))}
          </div>
          <div className="field-picker">
            <button className="ghost-btn small" onClick={() => setFieldPickerOpen(o => !o)}>
              <Icon name="filter" size={13} stroke={2}/> Fields ({fields.length})
            </button>
            {fieldPickerOpen && (
              <div className="field-picker-pop" onMouseLeave={() => setFieldPickerOpen(false)}>
                <div className="fp-section">
                  <div className="fp-label">Preset</div>
                  <div className="fp-presets">
                    {[['performance','Performance'],['compliance','Compliance'],['loyalty','Loyalty'],['engagement','Engagement']].map(([k,lbl]) => (
                      <button key={k} className={'fp-preset' + (preset === k ? ' is-on' : '')} onClick={() => applyPreset(k)}>{lbl}</button>
                    ))}
                  </div>
                </div>
                <div className="fp-section">
                  <div className="fp-label">Columns <span className="fp-hint">max 6</span></div>
                  <div className="fp-fields">
                    {Object.entries(FIELD_DEFS).map(([k, def]) => (
                      <label key={k} className={'fp-field' + (fields.includes(k) ? ' is-on' : '')}>
                        <input type="checkbox" checked={fields.includes(k)} onChange={() => toggleField(k)}/>
                        <span>{def.label}</span>
                      </label>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
          <button className="card-head-link">Export <Icon name="arrow-right" size={12} stroke={2.2}/></button>
        </div>
      </header>

      <div className="lb-table-wrap">
        <table className="lb-table">
          <thead>
            <tr>
              <th className="lb-col-rank">#</th>
              <SortHead label="Location"    sortKey="name"        current={sort.key} dir={sort.dir} onSort={onSort} tip="Shop name and city."/>
              <th>Type</th>
              {fields.map(f => {
                const def = FIELD_DEFS[f];
                return <SortHead key={f} label={def.label} sortKey={f} current={sort.key} dir={sort.dir} onSort={onSort} align={def.num ? 'right' : undefined} tip={def.info}/>;
              })}
              <th>10-day</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((l, i) => {
              const trendColor = l.sssYoY >= 0 ? '#16A34A' : '#DC2626';
              return (
                <tr key={l.id} onClick={() => onOpen(l)} className="lb-row">
                  <td className="lb-col-rank">
                    <div className={'rank-pill ' + (i < 2 ? 'is-top' : i >= rows.length - 2 ? 'is-bot' : '')}>{i+1}</div>
                  </td>
                  <td>
                    <div className="lb-name">{l.name}</div>
                    <div className="lb-sub">{l.city} · {l.id}</div>
                  </td>
                  <td><TypeBadge type={l.type}/></td>
                  {fields.map(f => (
                    <td key={f} className={FIELD_DEFS[f].num ? 'num' : ''}>
                      <FieldCell field={f} value={l[f]}/>
                    </td>
                  ))}
                  <td><Sparkline data={l.trend} color={trendColor}/></td>
                  <td><Compliance level={l.compliance} flags={l.flags}/></td>
                  <td className="lb-open"><Icon name="arrow-right" size={14} stroke={2}/></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </section>
  );
};

const SortHead = ({ label, sortKey, current, dir, onSort, align, tip }) => {
  const isOn = current === sortKey;
  return (
    <th className={'sort-head' + (align === 'right' ? ' right' : '')} onClick={() => onSort(sortKey)}>
      <span className="sort-head-inner">
        <span>{label}</span>
        {tip && <InfoDot tip={tip}/>}
        <span className={'sort-arrow' + (isOn ? ' is-on' : '')}>{isOn ? (dir === 'asc' ? '▲' : '▼') : '↕'}</span>
      </span>
    </th>
  );
};

Object.assign(window, { AlertRow, AlertCard, Leaderboard, Sparkline, Compliance, TypeBadge, PeriodPicker });
