// Interactive BI demo — KPI tiles + occupancy chart + heatmap + insight
// Reframed: scope spans more than buildings — HR/travel/engagement filters
function BIDemo() {
  const reports = ['Occupancy & Workplace', 'HR & Teams', 'Travel & Mobility', 'Engagement & Experience', 'Energy & ESG'];
  const ranges = ['7d', '30d', '90d', 'YTD'];

  const [report, setReport] = React.useState('Occupancy & Workplace');
  const [range, setRange] = React.useState('30d');

  // Seeded RNG so each (report,range) combo is stable
  const seed = React.useMemo(() => {
    let h = 0;const s = report + range;
    for (let i = 0; i < s.length; i++) h = h * 31 + s.charCodeAt(i) >>> 0;
    return h;
  }, [report, range]);
  const rngFn = React.useCallback((s) => {
    let st = s;
    return () => {st = st * 1103515245 + 12345 >>> 0;return (st >>> 8 & 0xFFFFFF) / 0xFFFFFF;};
  }, []);

  // Per-report config
  const cfg = {
    'Occupancy & Workplace': { primary: 'Avg occupancy', unit: '%', base: 68, k2: ['Peak utilisation', '%'], k3: ['Underused floors', '/ 38'], k4: ['Cost / seat', '$/day'] },
    'HR & Teams': { primary: 'Headcount on site', unit: '%', base: 64, k2: ['Team colocation', '%'], k3: ['Open seats', ''], k4: ['Resolution time', 'd'] },
    'Travel & Mobility': { primary: 'Travel vs office', unit: ' ratio', base: 1.3, k2: ['Trips this period', ''], k3: ['Avg cost / trip', '$'], k4: ['CO₂ per FTE', 'kg'] },
    'Engagement & Experience': { primary: 'Engagement score', unit: '', base: 38, k2: ['Survey response', '%'], k3: ['At-risk zones', ''], k4: ['Sentiment drift', 'pts'] },
    'Energy & ESG': { primary: 'kWh / m² / day', unit: '', base: 24, k2: ['Peak load', 'kW'], k3: ['Sustainability score', '/100'], k4: ['CO₂ vs FY24', '%'] }
  }[report];

  // Generate data
  const data = React.useMemo(() => {
    const rng = rngFn(seed);
    const N = range === '7d' ? 7 : range === '30d' ? 30 : range === '90d' ? 60 : 80;
    const series = [];let v = cfg.base;
    for (let i = 0; i < N; i++) {
      v += (rng() - 0.5) * cfg.base * 0.08;
      v = Math.max(cfg.base * 0.55, Math.min(cfg.base * 1.45, v * 0.82 + cfg.base * 0.18));
      series.push(v);
    }
    const avg = series.reduce((a, b) => a + b, 0) / series.length;
    const peak = Math.max(...series);

    const heat = [];
    for (let d = 0; d < 5; d++) {
      const row = [];
      for (let h = 0; h < 9; h++) {
        const peakBias = Math.exp(-Math.pow(h - 4, 2) / 5);
        const dayBias = d === 2 ? 1.1 : d === 4 ? 0.7 : 1.0;
        row.push(Math.max(8, Math.min(98, peakBias * dayBias * (60 + (rng() - 0.5) * 40))));
      }
      heat.push(row);
    }
    const bars = Array.from({ length: 6 }, (_, i) => ({ label: ['L1', 'L2', 'L3', 'L4', 'L5', 'L6'][i], v: Math.round(35 + rng() * 60) }));
    return { series, avg, peak, heat, bars };
  }, [seed, range, report, cfg.base, rngFn]);

  // chart geometry
  const W = 720,H = 200;
  const xs = data.series.map((_, i) => i / (data.series.length - 1) * W);
  const minV = Math.min(...data.series),maxV = Math.max(...data.series);
  const norm = (v) => H - (v - minV) / Math.max(0.01, maxV - minV) * H;
  const ys = data.series.map(norm);
  const path = xs.map((x, i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(' ');
  const area = path + ` L ${W},${H} L 0,${H} Z`;

  const fmt = (v, unit) => {
    if (unit === '%') return Math.round(v) + '%';
    if (unit.startsWith(' ratio')) return v.toFixed(1) + '×';
    if (unit === '$/day') return '$' + Math.round(34 + seed % 20);
    if (unit === '') return Math.round(v);
    return Math.round(v) + unit;
  };

  // KPI bag — varies by report
  const kpis = [
  { label: cfg.primary, value: fmt(data.avg, cfg.unit), delta: `+${(2.4 + seed % 6).toFixed(1)} pts`, dir: 'up', pts: data.series },
  { label: cfg.k2[0], value: fmt(data.peak, cfg.k2[1]), delta: 'Wed 14:00', dir: 'up', pts: data.series.slice().reverse() },
  { label: cfg.k3[0], value: `${4 + seed % 5}${cfg.k3[1]}`, delta: `${1 + seed % 3} flagged`, dir: 'down', pts: data.bars.map((b) => b.v) },
  { label: cfg.k4[0], value: cfg.k4[1] === '$/day' ? `$${34 + seed % 20}` : cfg.k4[1] === 'd' ? `${(2.2 + seed % 4 * 0.3).toFixed(1)}d` : cfg.k4[1] === '$' ? `$${120 + seed % 240}` : cfg.k4[1] === 'kg' ? `${24 + seed % 40}kg` : cfg.k4[1] === 'kW' ? `${80 + seed % 80}kW` : cfg.k4[1] === '/100' ? `${72 + seed % 18}` : cfg.k4[1] === '%' ? `${-12 - seed % 6}%` : cfg.k4[1] === 'pts' ? `${-1 - seed % 3}` : Math.round(data.avg), delta: cfg.k4[1] === '%' ? 'YoY' : 'rolling', dir: cfg.k4[1] === '%' ? 'up' : 'up', pts: data.series.map((v) => v * 0.8) }];


  // Insights bag
  const insights = {
    'Occupancy & Workplace': ['L3 and L7 trending below 50% for 4 consecutive weeks.', 'Consolidating L3 onto L4–5 would release ~1,420 sqm without exceeding 82% peak.'],
    'HR & Teams': ['Product team open-tickets resolution lengthening 18% MoM.', 'Cross-team colocation correlates with 11% faster resolution.'],
    'Travel & Mobility': ['Travel-to-office ratio peaks Tuesdays before regional all-hands.', 'Shifting 12% of travel to virtual could save ~A$184k / quarter.'],
    'Engagement & Experience': ['Zones L4-east & L6-west drove the engagement dip in last survey.', 'Quiet-zone availability is the strongest predictor of engagement this cycle.'],
    'Energy & ESG': ['Peak load moving 18 min earlier — heatwave correlated.', 'After-hours kWh / m² down 22% since LED + sensor retrofit.']
  }[report];

  // Heatmap headers vary by report
  const heatHead = report === 'Travel & Mobility' ? ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9'] : ['09', '10', '11', '12', '13', '14', '15', '16', '17'];
  const heatRows = report === 'Engagement & Experience' ? ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];

  return (
    <section className="bi-section">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="eyebrow on-dark"><span className="line" /><span>Business Intelligence</span></div>
            <h2 className="h-section" style={{ marginTop: 18, color: '#fff' }}>
              Business intelligence on top.<br />
              <em style={{ color: 'var(--orange-2)' }}>Operational data</em> underneath.
            </h2>
          </div>
          <p className="lead">
            We host your operational dashboards alongside to provide drill-downs.
            The surface stays clean — so leadership sees the headline and their teams
            can drill into the detail. Switch report, switch dates, and explore below.
          </p>
        </div>

        <div className="bi-shell">
          <div className="bi-head">
            <div className="l">
              <span className="title">Workplace Intelligence</span>
              <span className="crumb">/ {report} · {range}</span>
            </div>
            <div className="filters">
              {ranges.map((r) =>
              <button key={r} className={`filter-pill ${range === r ? 'active' : ''}`} onClick={() => setRange(r)}>{r}</button>
              )}
            </div>
          </div>

          <div className="bi-sub">
            <span className="lbl">Report</span>
            {reports.map((r) =>
            <button key={r} className={`filter-pill ${report === r ? 'active' : ''}`} onClick={() => setReport(r)}>{r}</button>
            )}
          </div>

          <div className="bi-grid">
            {kpis.map((k, i) =>
            <KPI key={i} col={3} {...k} />
            )}

            {/* trend chart */}
            <div className="bi-card" style={{ gridColumn: 'span 8' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <h4>{report} — daily trend</h4>
                  <div className="sub">{cfg.primary} · {range} window</div>
                </div>
                <div className="legend">
                  <span className="sw"><span className="sq" style={{ background: 'var(--orange)' }}></span>Current</span>
                  <span className="sw"><span className="sq" style={{ background: 'rgba(255,255,255,0.15)' }}></span>Target band</span>
                </div>
              </div>
              <svg viewBox={`0 0 ${W} ${H + 30}`} preserveAspectRatio="none" style={{ width: '100%', height: 220, marginTop: 14 }}>
                <defs>
                  <linearGradient id="biAreaFillDark" x1="0" x2="0" y1="0" y2="1">
                    <stop offset="0%" stopColor="var(--orange)" stopOpacity="0.32" />
                    <stop offset="100%" stopColor="var(--orange)" stopOpacity="0" />
                  </linearGradient>
                </defs>
                {[0, 0.25, 0.5, 0.75, 1].map((p, i) =>
                <line key={i} x1="0" x2={W} y1={p * H} y2={p * H}
                stroke="rgba(255,255,255,0.07)" strokeWidth="1"
                strokeDasharray={p === 0.5 ? '0' : '2 4'} />
                )}
                <rect x="0" y={H * 0.25} width={W} height={H * 0.3} fill="rgba(255,255,255,0.025)" />
                <path d={area} fill="url(#biAreaFillDark)" style={{ transition: 'd .4s' }} />
                <path d={path} stroke="var(--orange-2)" strokeWidth="1.6" fill="none" strokeLinejoin="round" strokeLinecap="round" />
                {xs.map((x, i) => i % Math.max(1, Math.floor(xs.length / 8)) === 0 &&
                <circle key={i} cx={x} cy={ys[i]} r="2.5" fill="#fff" />
                )}
                {(() => {
                  const labels = range === '7d' ? ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] :
                  range === '30d' ? ['W1', 'W2', 'W3', 'W4'] :
                  range === '90d' ? ['M1', 'M2', 'M3'] :
                  ['Q1', 'Q2', 'Q3', 'YTD'];
                  return labels.map((l, i) =>
                  <text key={l} x={i / (labels.length - 1) * W} y={H + 18}
                  textAnchor={i === 0 ? 'start' : i === labels.length - 1 ? 'end' : 'middle'}
                  fontFamily="DM Sans, sans-serif" fontSize="10" fill="rgba(255,255,255,0.4)" letterSpacing="0.08em">{l.toUpperCase()}</text>
                  );
                })()}
              </svg>
            </div>

            {/* bar chart — floors/groups */}
            <div className="bi-card" style={{ gridColumn: 'span 4' }}>
              <div>
                <h4>By group</h4>
                <div className="sub">{report === 'HR & Teams' ? 'Teams' : report === 'Travel & Mobility' ? 'Regions' : 'Floors'}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
                {data.bars.map((b, i) => {
                  const tone = b.v < 55 ? 'rgba(255,255,255,0.35)' : b.v < 78 ? 'var(--orange)' : 'var(--orange-2)';
                  return (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'DM Sans, sans-serif', fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>
                      <span style={{ width: 28, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.06em' }}>{b.label}</span>
                      <div style={{ flex: 1, height: 12, background: 'rgba(255,255,255,0.05)', borderRadius: 2, overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: `${b.v}%`, background: tone, transition: 'width .6s cubic-bezier(.2,.8,.2,1)' }} />
                      </div>
                      <span style={{ width: 36, textAlign: 'right' }}>{b.v}%</span>
                    </div>);

                })}
              </div>
            </div>

            {/* heatmap */}
            <div className="bi-card" style={{ gridColumn: 'span 8' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <h4>Pattern</h4>
                  <div className="sub">{report === 'Travel & Mobility' ? 'Quarter × week — trip density' : 'Hours × days — activity level'}</div>
                </div>
                <div className="legend">
                  <span className="mono" style={{ color: 'rgba(255,255,255,0.45)' }}>Low</span>
                  {[0.15, 0.3, 0.5, 0.7, 0.9].map((a, i) =>
                  <span key={i} className="sq" style={{ background: `rgba(232,97,26,${a})`, width: 14, height: 14 }} />
                  )}
                  <span className="mono" style={{ color: 'rgba(255,255,255,0.45)' }}>High</span>
                </div>
              </div>
              <div className="heatmap" style={{ gridTemplateColumns: '56px repeat(9, 1fr)' }}>
                <div></div>
                {heatHead.map((h) => <div className="colhead" key={h}>{h}</div>)}
                {heatRows.map((d, di) =>
                <React.Fragment key={d}>
                    <div className="lbl">{d}</div>
                    {data.heat[di].map((v, hi) => {
                    const a = Math.min(0.96, Math.max(0.06, v / 100));
                    return (
                      <div key={hi} className="cell"
                      title={`${d} ${heatHead[hi]} — ${Math.round(v)}%`}
                      style={{ background: `rgba(232,97,26,${a.toFixed(2)})`, transition: 'background .4s' }} />);

                  })}
                  </React.Fragment>
                )}
              </div>
            </div>

            {/* insight */}
            <div className="bi-card" style={{ gridColumn: 'span 4', background: 'rgba(232,97,26,0.08)', border: '1px solid rgba(232,97,26,0.3)' }}>
              <div className="mono" style={{ color: 'var(--orange-2)', letterSpacing: '0.12em' }}>INSIGHT — AUTO</div>
              <h4 style={{ color: '#fff', marginTop: 12, fontSize: 18, fontFamily: 'var(--display)', fontWeight: 400, lineHeight: 1.3 }}>
                {insights[0]}
              </h4>
              <p style={{ color: 'rgba(255,255,255,0.6)', fontSize: 13, marginTop: 12, lineHeight: 1.65 }}>
                {insights[1]}
              </p>
              <a href="#contact" style={{ color: 'var(--orange-2)', marginTop: 16, display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: 'DM Sans, sans-serif' }}
              onClick={(e) => {e.preventDefault();document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' });}}>
                Open scenario <Icon.arr />
              </a>
            </div>
          </div>

          <div className="bi-foot">
            <div className="l">Refreshed automatically every weeknight · Power BI workspace · last sync 06:00 AEST</div>
            <div className="bi-badge">
              <div className="box" />
              <div className="t">Power BI</div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

function KPI({ col, label, value, delta, dir, pts }) {
  const W = 120,H = 28;
  const min = Math.min(...pts),max = Math.max(...pts);
  const d = pts.map((p, i) => {
    const x = i / (pts.length - 1) * W;
    const y = H - (p - min) / (max - min || 1) * H;
    return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  return (
    <div className="kpi-tile" style={{ gridColumn: `span ${col}` }}>
      <div className="l">{label}</div>
      <div className="v">{value}</div>
      <div className={`d ${dir === 'down' ? 'down' : ''}`}>{dir === 'down' ? <Icon.down /> : <Icon.up />}{delta}</div>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="spark" style={{ width: '100%' }}>
        <path d={d} fill="none" stroke="var(--orange-2)" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    </div>);

}

window.BIDemo = BIDemo;