const Sparkline = ({ data, w = 80, h = 22 }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const span = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / span) * (h - 2) - 1;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: w, height: h }}>
      <polyline points={pts} fill="none" stroke="var(--accent)" strokeWidth="1.25" />
    </svg>
  );
};

const Hero = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  const d = window.__data;
  const todayLabel = new Date().toLocaleDateString(window.__lang === 'ar' ? 'ar-QA' : 'en-US', { weekday: 'long', day: 'numeric', month: 'short' });
  const heroLabel = t('ov.heroBig.label') + ' · ' + todayLabel;
  const heroFooterMap = { 'vs. last Sun': t('ov.heroFooter.vsLastSun'), 'no-shows MTD': t('ov.heroFooter.noShowMtd'), 'avg. wait': t('ov.heroFooter.avgWait') };
  const heroKpiMap = { 'Bookings today': t('ov.heroKpi.bookings'), 'Response SLA': t('ov.heroKpi.responseSla') };
  const unitMap = { 'slots': t('ov.unit.slots'), 'min avg': t('ov.unit.minAvg'), 'min': t('ov.unit.min') };
  const ctxMap = { 'first reply': t('ov.context.firstReply'), 'vs. last Sun': t('ov.heroFooter.vsLastSun') };
  return (
    <div className="card" style={{ marginBottom: 16 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 1fr', gap: 0 }}>
        <div style={{ padding: '24px 26px', borderRight: '1px solid var(--line)' }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.14em', marginBottom: 6 }}>{heroLabel}</div>
          <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 44, fontWeight: 500, lineHeight: 1 }}>
            {d.heroBig.value}<span style={{ fontSize: 18, color: 'var(--fg-3)', fontStyle: 'normal', fontFamily: 'var(--sans)', marginLeft: 10 }}>{unitMap[d.heroBig.unit] || d.heroBig.unit}</span>
          </div>
          <p style={{ margin: '14px 0 0', color: 'var(--fg-2)', fontSize: 13.5, lineHeight: 1.6, maxWidth: 580 }}>{t('ov.heroStatement')}</p>
          <div style={{ display: 'flex', gap: 22, marginTop: 16, flexWrap: 'wrap' }}>
            {d.heroFooter.map((f, i) => (
              <div key={i}>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 15, fontWeight: 600 }}>{f.value}</span>
                <span style={{ color: 'var(--fg-3)', fontSize: 12, marginLeft: 6 }}>· {heroFooterMap[f.label] || f.label}</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '24px 22px', display: 'flex', flexDirection: 'column', gap: 18 }}>
          {d.heroKpis.map((k, i) => (
            <div key={i}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.14em' }}>{heroKpiMap[k.label] || k.label}</div>
              <div style={{ fontSize: 24, fontWeight: 600, marginTop: 4 }}>
                {k.value}<span style={{ fontSize: 12, color: 'var(--fg-3)', marginLeft: 6, fontWeight: 400 }}>{unitMap[k.unit] || k.unit}</span>
              </div>
              <div style={{ display: 'flex', gap: 10, fontSize: 11, marginTop: 2 }}>
                <span style={{ color: k.deltaDir === 'pos' ? 'var(--pos)' : 'var(--neg)', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                  <Icon name={k.deltaDir === 'pos' ? 'arrowUp' : 'arrowDown'} size={10} /> {k.delta}
                </span>
                <span style={{ color: 'var(--fg-3)' }}>{ctxMap[k.context] || k.context}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const KpiRow = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  const labelMap = {
    "Today's bookings": t('ov.kpi.bookings'),
    'Doctor utilisation': t('ov.kpi.utilisation'),
    'No-show rate': t('ov.kpi.noShow'),
    'New patients (MTD)': t('ov.kpi.newPatients')
  };
  const ctxMap = { 'vs. last Sun': t('ov.heroFooter.vsLastSun'), 'target 80': t('ov.kpi.context.target80'), 'target < 5': t('ov.kpi.context.target5'), 'vs. prior': t('ov.kpi.context.vsPrior') };
  const unitMap = { 'slots': t('ov.unit.slots') };
  return (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 16 }}>
    {window.__data.kpis.map((k, i) => (
      <div className="card" key={i} style={{ padding: '16px 18px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>{labelMap[k.label] || k.label}</div>
          <Sparkline data={k.spark} />
        </div>
        <div style={{ fontSize: 26, fontWeight: 600, fontFamily: 'var(--serif)', fontStyle: 'italic' }}>
          {k.value}{k.unit && <span style={{ fontSize: 12, color: 'var(--fg-3)', marginLeft: 6, fontStyle: 'normal', fontFamily: 'var(--sans)', fontWeight: 400 }}>{unitMap[k.unit] || k.unit}</span>}
        </div>
        <div style={{ display: 'flex', gap: 10, fontSize: 11, marginTop: 2 }}>
          <span style={{ color: k.deltaDir === 'pos' ? 'var(--pos)' : 'var(--neg)', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
            <Icon name={k.deltaDir === 'pos' ? 'arrowUp' : 'arrowDown'} size={10} /> {k.delta}
          </span>
          <span style={{ color: 'var(--fg-3)' }}>{ctxMap[k.context] || k.context}</span>
        </div>
      </div>
    ))}
  </div>
  );
};

const BookingsChart = () => {
  const { labels, actual, target } = window.__data.revenue;
  const w = 620, h = 230, pad = { l: 44, r: 14, t: 18, b: 28 };
  const max = Math.max(...actual, ...target) * 1.1;
  const xStep = (w - pad.l - pad.r) / (labels.length - 1);
  const yScale = v => h - pad.b - (v / max) * (h - pad.t - pad.b);
  const linePts = arr => arr.map((v, i) => `${pad.l + i * xStep},${yScale(v)}`).join(' ');
  const areaPath = arr => {
    const pts = arr.map((v, i) => `${pad.l + i * xStep},${yScale(v)}`);
    return `M ${pad.l},${yScale(0)} L ${pts.join(' L ')} L ${pad.l + (arr.length - 1) * xStep},${yScale(0)} Z`;
  };
  const yTicks = [0, 1000, 2000, 3000, 4000].filter(v => v <= max);
  return (
    <div className="card">
      <div className="card-head">
        <div>
          <div className="sub">{(window.__t ? window.__t('ov.chart.sub') : 'Last 12 months · bookings / month')}</div>
          <h3>{(window.__t ? window.__t('ov.chart.title').replace(window.__t('ov.chart.title.em'), '').trim() : 'Booking')} <em>{(window.__t ? window.__t('ov.chart.title.em') : 'volume')}</em></h3>
        </div>
        <div className="pill-tabs"><button>30D</button><button>90D</button><button className="active">12M</button></div>
      </div>
      <div style={{ padding: '0 18px 18px' }}>
        <svg width="100%" viewBox={`0 0 ${w} ${h}`} style={{ maxWidth: '100%', display: 'block' }}>
          <defs>
            <linearGradient id="aFill" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.28" />
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
            </linearGradient>
          </defs>
          {yTicks.map((v, i) => (
            <g key={i}>
              <line x1={pad.l} x2={w - pad.r} y1={yScale(v)} y2={yScale(v)} stroke="var(--line)" strokeDasharray={v === 0 ? '' : '2 4'} />
              <text x={pad.l - 8} y={yScale(v) + 3} textAnchor="end" fill="var(--fg-3)" fontSize="9" fontFamily="var(--mono)">{v}</text>
            </g>
          ))}
          {labels.map((l, i) => (
            <text key={l} x={pad.l + i * xStep} y={h - 10} textAnchor="middle" fill="var(--fg-3)" fontSize="9" fontFamily="var(--mono)" letterSpacing="0.1em">{l}</text>
          ))}
          <path d={areaPath(actual)} fill="url(#aFill)" />
          <polyline points={linePts(target)} fill="none" stroke="var(--fg-3)" strokeWidth="1.1" strokeDasharray="3 3" />
          <polyline points={linePts(actual)} fill="none" stroke="var(--accent)" strokeWidth="1.75" />
          {actual.map((v, i) => (
            <circle key={i} cx={pad.l + i * xStep} cy={yScale(v)} r="2.25" fill="var(--bg-elev)" stroke="var(--accent)" strokeWidth="1.25" />
          ))}
        </svg>
      </div>
    </div>
  );
};

const SpecialtiesCard = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  return (
  <div className="card">
    <div className="card-head">
      <div>
        <div className="sub">{t('ov.spec.sub')}</div>
        <h3>{t('ov.spec.title').replace(t('ov.spec.title.em'), '').trim()} <em>{t('ov.spec.title.em')}</em></h3>
      </div>
      <span className="tag accent">142 {t('ov.spec.total')}</span>
    </div>
    <div className="card-body flush">
      {window.__data.specialties.map((s, i) => {
        const max = Math.max(...window.__data.specialties.map(x => x.bookings_today));
        return (
          <div key={s.code} style={{ padding: '10px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', display: 'grid', gridTemplateColumns: '1fr 50px 100px', gap: 10, alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }} />
              <span style={{ fontSize: 12.5, fontWeight: 500 }}>{s.name}</span>
              <span className="mono" style={{ fontSize: 9.5, color: 'var(--fg-4)', letterSpacing: '0.06em' }}>{s.code}</span>
            </div>
            <div className="mono" style={{ fontSize: 12, fontWeight: 600, textAlign: 'right' }}>{s.bookings_today}</div>
            <div style={{ height: 5, background: 'var(--bg-soft)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${(s.bookings_today / max) * 100}%`, background: s.color }} />
            </div>
          </div>
        );
      })}
    </div>
  </div>
  );
};

const ActivityFeed = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  return (
  <div className="card">
    <div className="card-head">
      <div>
        <div className="sub">{t('ov.activity.sub')}</div>
        <h3><em>{t('ov.activity.title.em')}</em> {t('ov.activity.title').replace(t('ov.activity.title.em'), '').trim()}</h3>
      </div>
      <button className="btn ghost">{t('common.viewAll')}</button>
    </div>
    <div className="card-body flush">
      {window.__data.activity.map((a, i) => (
        <div key={i} style={{ padding: '11px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', display: 'grid', gridTemplateColumns: '52px 1fr auto', gap: 10, alignItems: 'center', fontSize: 12.5 }}>
          <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-3)', letterSpacing: '0.06em' }}>{a.time}</div>
          <div>
            <span style={{ fontWeight: 500 }}>{a.who}</span>{' '}
            <span style={{ color: 'var(--fg-2)' }}>{a.what}</span>{' '}
            <span style={{ color: 'var(--accent-deep)' }}>{a.target}</span>
          </div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{a.amt}</div>
        </div>
      ))}
    </div>
  </div>
  );
};

const DoctorsCard = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  return (
  <div className="card">
    <div className="card-head">
      <div>
        <div className="sub">{window.__data.topDoctors.length} {t('ov.doctors.subPrefix')} · {t('ov.doctors.sub')}</div>
        <h3><em>{t('ov.doctors.title.em')}</em> {t('ov.doctors.title').replace(t('ov.doctors.title.em'), '').trim()}</h3>
      </div>
    </div>
    <div className="card-body flush">
      <div style={{ display: 'grid', gridTemplateColumns: '32px 1fr 1fr 80px 90px', padding: '10px 18px', borderBottom: '1px solid var(--line)', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.1em', gap: 12 }}>
        <div></div><div>{t('ov.doctors.col.doctor')}</div><div>{t('ov.doctors.col.specialty')}</div><div>{t('ov.doctors.col.today')}</div><div>{t('ov.doctors.col.util')}</div>
      </div>
      {window.__data.topDoctors.map((doc, i) => (
        <div key={doc.ref} style={{ display: 'grid', gridTemplateColumns: '32px 1fr 1fr 80px 90px', padding: '12px 18px', borderTop: '1px solid var(--line)', alignItems: 'center', gap: 12, fontSize: 13 }}>
          <div style={{ width: 28, height: 28, borderRadius: 6, background: 'var(--accent-soft)', color: 'var(--accent-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700 }}>{doc.name.split(' ').slice(-1)[0].slice(0,2).toUpperCase()}</div>
          <div style={{ fontWeight: 500 }}>{doc.name}</div>
          <div style={{ color: 'var(--fg-2)', fontSize: 12 }}>{doc.specialty}</div>
          <div className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{doc.appointments}</div>
          <div>
            <div style={{ height: 5, background: 'var(--bg-soft)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${doc.utilisation}%`, background: doc.utilisation >= 85 ? 'var(--pos)' : 'var(--accent)' }} />
            </div>
            <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', marginTop: 3 }}>{doc.utilisation}%</div>
          </div>
        </div>
      ))}
    </div>
  </div>
  );
};

const Overview = () => (
  <div className="content view">
    <Hero />
    <KpiRow />
    <div className="grid cols-3" style={{ marginBottom: 16 }}>
      <BookingsChart />
      <SpecialtiesCard />
    </div>
    <div className="grid cols-2-3" style={{ marginBottom: 16 }}>
      <ActivityFeed />
      <DoctorsCard />
    </div>
  </div>
);

window.Overview = Overview;
