// "Dashboard" preview — animated KPI mockup of what a client sees after launch.
// IntersectionObserver triggers count-up animations once on scroll-in.

const SPARKLINE = [12, 18, 14, 22, 19, 28, 31, 41, 35, 48, 52, 47, 61, 58, 72];

const FEED_INIT = [
  { t: '09:42', biz: 'Lake Norman Dental', kind: 'NEW PATIENT', note: 'Booked Wed 9:10 AM · intake sent', flag: 'lead' },
  { t: '09:18', biz: 'Carolina Comfort HVAC', kind: 'EMERGENCY', note: '2 PM dispatch · est. ticket $4.2k', flag: 'high' },
  { t: '08:54', biz: 'Brightline Law', kind: 'CONSULT', note: 'Couple + minors · Thu 10 AM w/ Sarah', flag: 'lead' },
  { t: '08:31', biz: 'Aurora Pilates', kind: 'NEW CLIENT', note: 'First-class trial · Sat 9 AM', flag: 'lead' },
  { t: '08:12', biz: 'Lake Norman Dental', kind: 'INFO', note: 'Insurance check · no booking yet', flag: 'info' },
];

// Hook: arm once the parent comes into view
function useArm(threshold = 0.1) {
  const ref = React.useRef(null);
  const [armed, setArmed] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current || armed) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) setArmed(true);
    }, { threshold });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [armed, threshold]);
  return [armed, ref];
}

// Hook: count from 0 to target once armed
function useCountUp(target, armed, duration = 1100) {
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    if (!armed) return;
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const p = Math.min(1, (now - start) / duration);
      const ease = 1 - Math.pow(1 - p, 3);
      setVal(target * ease);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [armed, target, duration]);
  return val;
}

function DashboardSection() {
  const [armed, surfaceRef] = useArm(0.08);
  const conv = useCountUp(248, armed);
  const leads = useCountUp(31, armed);
  const rt = useCountUp(4.2, armed);
  const hrs = useCountUp(36, armed);

  const fmt = (n, d = 0) => Number(n.toFixed(d)).toLocaleString();

  // live feed: rotate top entry every 6s to suggest "real time"
  const [feed, setFeed] = React.useState(FEED_INIT);
  React.useEffect(() => {
    const id = setInterval(() => {
      setFeed(prev => {
        const next = [...prev];
        const t = new Date(Date.now() - Math.random() * 600000);
        const pad = (n) => String(n).padStart(2, '0');
        const newEntry = {
          ...FEED_INIT[Math.floor(Math.random() * FEED_INIT.length)],
          t: `${pad(t.getHours())}:${pad(t.getMinutes())}`,
        };
        return [newEntry, ...next.slice(0, 4)];
      });
    }, 6000);
    return () => clearInterval(id);
  }, []);

  const dashStyles = {
    sec: { padding: '120px 0', background: TOKEN.paper, color: TOKEN.ink, position: 'relative' },
    surface: {
      background: TOKEN.paperDeep, border: `1px solid ${TOKEN.hair}`,
      padding: 0, position: 'relative',
    },
    bar: {
      borderBottom: `1px solid ${TOKEN.hair}`,
      padding: '16px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: '#fff',
    },
    body: { padding: 24 },
    kpiGrid: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0,
      background: '#fff', border: `1px solid ${TOKEN.hair}`,
    },
    kpi: { padding: '24px 24px 22px', borderRight: `1px solid ${TOKEN.hair}` },
    kpiNum: {
      fontFamily: '"IBM Plex Sans"', fontWeight: 500, fontSize: 44,
      letterSpacing: -1.5, lineHeight: 1, color: TOKEN.ink,
      fontVariantNumeric: 'tabular-nums', display: 'flex', alignItems: 'baseline', gap: 4,
    },
    panel: { background: '#fff', border: `1px solid ${TOKEN.hair}`, padding: 24, marginTop: 16 },
  };

  return (
    <section id="dashboard" style={dashStyles.sec}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 48, marginBottom: 56 }}>
          <div>
            <SectionLabel num="04" accent={TOKEN.orange}>Dashboard</SectionLabel>
            <h2 style={{
              fontFamily: '"IBM Plex Sans", system-ui, sans-serif',
              fontWeight: 600, fontSize: 44, letterSpacing: -1.4, lineHeight: 1.08,
              margin: '20px 0 0', color: TOKEN.ink, maxWidth: 460,
            }}>Numbers, not <em style={{ fontFamily: '"IBM Plex Serif"', fontStyle: 'italic', fontWeight: 400, color: TOKEN.orange }}>vibes.</em></h2>
          </div>
          <div style={{
            fontSize: 18, lineHeight: 1.55, color: TOKEN.mute,
            letterSpacing: -0.2, maxWidth: 560, paddingTop: 28,
          }}>
            Every week, you get conversation logs, leads captured, hours saved, and response-time deltas. The dashboard below is mocked from a real client's week 19.
          </div>
        </div>

        <div style={dashStyles.surface} ref={surfaceRef}>
          <CornerMark where="tl"/><CornerMark where="tr"/><CornerMark where="bl"/><CornerMark where="br"/>

          {/* status bar */}
          <div style={dashStyles.bar}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <Wordmark size={14}/>
              <span style={{ width: 1, height: 18, background: TOKEN.hair }}/>
              <Mono color={TOKEN.inkSoft} size={11}>LAKE NORMAN DENTAL · WEEK 19</Mono>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <Mono color={TOKEN.mute}>Last sync · 42 sec ago</Mono>
              <span style={{ width: 7, height: 7, borderRadius: 99, background: TOKEN.green, boxShadow: `0 0 0 3px rgba(31,138,91,0.22)` }}/>
              <Mono color={TOKEN.green} weight={600}>LIVE</Mono>
            </div>
          </div>

          {/* KPI grid */}
          <div style={dashStyles.body}>
            <div style={dashStyles.kpiGrid}>
              <Kpi label="CONVERSATIONS · 7D"
                value={fmt(conv)}
                delta="+18%"
                sub="vs week 18"
                bar/>
              <Kpi label="LEADS CAPTURED"
                value={fmt(leads)}
                delta="+12.5%"
                sub="qualified hand-off"/>
              <Kpi label="AVG RESPONSE TIME"
                value={fmt(rt, 1)} unit="sec"
                delta="−83%"
                sub="vs front desk baseline"
                deltaColor={TOKEN.green}/>
              <Kpi label="HOURS SAVED · 7D"
                value={fmt(hrs)} unit="hr"
                delta="$1,260"
                sub="@ $35/hr equivalent"
                deltaColor={TOKEN.orange} last/>
            </div>

            {/* main row: chart + feed */}
            <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16, marginTop: 16 }}>
              {/* Sparkline chart */}
              <div style={dashStyles.panel}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
                  <Mono color={TOKEN.orange} weight={600}>CONVERSATIONS · LAST 15 DAYS</Mono>
                  <Mono color={TOKEN.mute}>HOURLY · 24H AVG</Mono>
                </div>
                <Sparkline data={SPARKLINE}/>
                <div style={{
                  display: 'flex', justifyContent: 'space-between',
                  marginTop: 12, paddingTop: 12, borderTop: `1px solid ${TOKEN.hair}`,
                }}>
                  <Stat k="PEAK" v="72/day"/>
                  <Stat k="TOTAL" v="558"/>
                  <Stat k="WEEKDAY AVG" v="42"/>
                  <Stat k="WEEKEND AVG" v="51"/>
                </div>
              </div>

              {/* Live feed */}
              <div style={dashStyles.panel}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
                  <Mono color={TOKEN.orange} weight={600}>RECENT ACTIVITY</Mono>
                  <Mono color={TOKEN.mute}>AUTO-REFRESH</Mono>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                  {feed.map((f, i) => <FeedRow key={`${f.t}-${i}-${f.biz}`} item={f} fresh={i === 0}/>)}
                </div>
              </div>
            </div>

            {/* funnel strip */}
            <div style={{
              ...dashStyles.panel, marginTop: 16,
              display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 0, padding: 0,
            }}>
              {[
                { l: 'Visitors', v: '1,842', pct: 100 },
                { l: 'Engaged agent', v: '603', pct: 33 },
                { l: 'Qualified', v: '124', pct: 7 },
                { l: 'Hand-off to human', v: '31', pct: 2 },
                { l: 'Booked / sold', v: '22', pct: 1 },
              ].map((s, i, arr) => (
                <div key={s.l} style={{
                  padding: 20, borderRight: i < arr.length - 1 ? `1px solid ${TOKEN.hair}` : 'none',
                  position: 'relative',
                }}>
                  <Mono color={TOKEN.mute}>STEP {String(i+1).padStart(2,'0')}</Mono>
                  <div style={{
                    fontFamily: '"IBM Plex Sans"', fontWeight: 500, fontSize: 24,
                    letterSpacing: -0.6, color: TOKEN.ink, marginTop: 6, lineHeight: 1,
                    fontVariantNumeric: 'tabular-nums',
                  }}>{s.v}</div>
                  <div style={{ fontSize: 13, color: TOKEN.inkSoft, marginTop: 6, letterSpacing: -0.1 }}>{s.l}</div>
                  {/* tiny bar */}
                  <div style={{ marginTop: 14, height: 3, background: TOKEN.hair }}>
                    <div style={{
                      height: '100%', width: `${s.pct}%`,
                      background: i < 3 ? TOKEN.ink : TOKEN.orange,
                      transition: 'width 1s ease',
                    }}/>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Kpi({ label, value, unit, delta, sub, last, bar, deltaColor = TOKEN.blue }) {
  return (
    <div style={{
      padding: '24px 24px 22px',
      borderRight: last ? 'none' : `1px solid ${TOKEN.hair}`,
      position: 'relative',
    }}>
      <Mono color={TOKEN.orange} weight={600}>{label}</Mono>
      <div style={{
        fontFamily: '"IBM Plex Sans"', fontWeight: 500, fontSize: 44,
        letterSpacing: -1.5, lineHeight: 1, color: TOKEN.ink,
        fontVariantNumeric: 'tabular-nums',
        marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 6,
      }}>
        {value}
        {unit && <span style={{ fontSize: 16, color: TOKEN.mute, fontWeight: 400, letterSpacing: -0.2 }}>{unit}</span>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14 }}>
        <span style={{
          fontFamily: '"IBM Plex Mono", monospace', fontSize: 11, fontWeight: 600,
          color: deltaColor, letterSpacing: 0.4,
          padding: '3px 6px', background: deltaColor + '14',
        }}>{delta}</span>
        <span style={{ fontSize: 12, color: TOKEN.mute, letterSpacing: -0.05 }}>{sub}</span>
      </div>
    </div>
  );
}

function Sparkline({ data }) {
  const max = Math.max(...data);
  const w = 100 / data.length;
  return (
    <svg viewBox={`0 0 100 36`} preserveAspectRatio="none" style={{ width: '100%', height: 110, display: 'block' }}>
      {/* axis */}
      <line x1="0" y1="36" x2="100" y2="36" stroke={TOKEN.hair} strokeWidth="0.3"/>
      {/* bars */}
      {data.map((v, i) => {
        const h = (v / max) * 32;
        const peak = v === max;
        return (
          <g key={i}>
            <rect x={i * w + 1} y={36 - h} width={w - 2} height={h}
              fill={peak ? TOKEN.orange : (i >= data.length - 3 ? TOKEN.ink : TOKEN.inkSoft)}/>
          </g>
        );
      })}
      {/* trend line */}
      <polyline
        points={data.map((v, i) => `${i * w + w/2},${36 - (v / max) * 32}`).join(' ')}
        fill="none" stroke={TOKEN.blue} strokeWidth="0.6" strokeLinejoin="round"
        style={{ opacity: 0.5 }}
      />
    </svg>
  );
}

function FeedRow({ item, fresh }) {
  const flagColor = item.flag === 'high' ? TOKEN.orange : (item.flag === 'lead' ? TOKEN.blue : TOKEN.mute);
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 12,
      padding: '10px 0', borderTop: `1px solid ${TOKEN.hair}`,
      alignItems: 'baseline',
      animation: fresh ? 'demo-in .4s ease both' : 'none',
    }}>
      <Mono color={TOKEN.mute} style={{ fontVariantNumeric: 'tabular-nums' }}>{item.t}</Mono>
      <div>
        <div style={{ fontFamily: '"IBM Plex Sans"', fontSize: 13, fontWeight: 500, color: TOKEN.ink, letterSpacing: -0.15 }}>
          {item.biz}
        </div>
        <div style={{ fontSize: 12, color: TOKEN.mute, marginTop: 2, letterSpacing: -0.05 }}>{item.note}</div>
      </div>
      <Mono color={flagColor} weight={600} size={9}>{item.kind}</Mono>
    </div>
  );
}

function Stat({ k, v }) {
  return (
    <div>
      <Mono color={TOKEN.mute}>{k}</Mono>
      <div style={{
        fontFamily: '"IBM Plex Sans"', fontSize: 16, fontWeight: 600,
        color: TOKEN.ink, marginTop: 4, letterSpacing: -0.2,
        fontVariantNumeric: 'tabular-nums',
      }}>{v}</div>
    </div>
  );
}

Object.assign(window, { DashboardSection });
