// Dashboard — "the control room". Compliance-deadline spine (the wedge),
// live pulse, omni-channel intake, and the voice-first field moment.
function Dashboard({ onBuilding, onNav, persona }) {
  const globeRef = React.useRef(null);
  React.useEffect(() => {
    if (globeRef.current && window.OpsGlobe) window.OpsGlobe.init(globeRef.current);
  }, []);

  // Scope: treasurer = Harbourview only, building manager = The Lumen only,
  // strata and maintenance see everything.
  const scopeBldg =
    persona && persona.id === 'treasurer' ? 'Harbourview' :
    persona && persona.id === 'building'  ? 'The Lumen' :
    null;
  const SCOPED_DEADLINES = scopeBldg ? DEADLINES.filter(d => (d.bldg || '').startsWith(scopeBldg)) : DEADLINES;
  const SCOPED_INTAKE    = scopeBldg ? INTAKE.filter(it => (it.bldg || '').startsWith(scopeBldg))    : INTAKE;
  const SCOPED_BOARD     = scopeBldg
    ? BOARD.map(col => ({ ...col, jobs: col.jobs.filter(j => (j.bldg || '').startsWith(scopeBldg)) }))
    : BOARD;
  const hero = (persona && persona.hero) || {};

  // Accordion: each deadline's AI suggestion is collapsed by default and drops
  // down on its chevron. "Expand all" toggles every AI-bearing row at once.
  const aiIdx = SCOPED_DEADLINES.map((d, i) => (d.ai && d.ai.action) ? i : null).filter(x => x !== null);
  const [open, setOpen] = React.useState({});
  const allOpen = aiIdx.length > 0 && aiIdx.every(i => open[i]);
  const toggleAll = () => {
    if (allOpen) { setOpen({}); }
    else { const o = {}; aiIdx.forEach(i => { o[i] = true; }); setOpen(o); }
  };
  const toggleOne = (i) => setOpen(p => ({ ...p, [i]: !p[i] }));
  return (
    <div className="view">
      <div className="dash-hero">
        <canvas ref={globeRef} className="globe" data-ops-globe data-points="360" data-active="6"></canvas>
        <div className="z">
          <div>
            <div className="eyebrow">{hero.eyebrow || 'Monday, 8 June 2026 · 127 schemes · 4,180 lots'}</div>
            <h1 dangerouslySetInnerHTML={{ __html: hero.h1 || 'Good morning, Jessica.<br />Eight deadlines need you <em>today.</em>' }} />
            <div className="sub">{hero.sub || 'The control room is calm. Across 127 schemes, here is what moves the book forward this morning.'}</div>
          </div>
          <div className="hero-pulse">
            {(hero.pulse || [['8','Due ≤ 48h',true],['34','In intake'],['2h 10m','Avg response'],['93.6%','Compliance']]).map(([n,l,alert],i) => (
              <div className="cell" key={i}><div className={`n ${alert?'alert':''}`}>{n}</div><div className="l">{l}</div></div>
            ))}
          </div>
        </div>
      </div>

      <div className="dash-board-strip">
        <div className="card">
          <div className="card-h">
            <h3>Job board</h3>
            <span className="more" onClick={() => onNav('board')}>Open board <Icon name="arrow-right" /></span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6,1fr)', gap: 1, background: 'var(--line-1)', padding: 1 }}>
            {SCOPED_BOARD.map(col => (
              <div key={col.key} style={{ background: 'var(--navy-800)', padding: '14px 16px', cursor: 'pointer' }} onClick={() => onNav('board')}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--fg-3)' }}>
                  <span style={{ width: 6, height: 6, borderRadius: 9, background: col.dot }} />{col.name}
                </div>
                <div style={{ fontSize: 26, color: 'var(--fg-1)', marginTop: 10, fontVariantNumeric: 'tabular-nums' }}>{col.jobs.length}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="dash-grid">
        <div className="stack">
          <div className="card">
            <div className="card-h">
              <h3>Days to deadline</h3>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                {aiIdx.length > 0 && (
                  <button className="exp-all" onClick={toggleAll}>
                    <Icon name={allOpen ? 'chevrons-down-up' : 'chevrons-up-down'} />
                    {allOpen ? 'Collapse all' : 'Expand all'}
                  </button>
                )}
                <span className="more" onClick={() => onNav('compliance')}>23 live · tracker <Icon name="arrow-right" /></span>
              </div>
            </div>
            {SCOPED_DEADLINES.map((d, i) => {
              const hasAi = d.ai && d.ai.action;
              const isOpen = !!open[i];
              return (
              <div className="deadline-wrap" key={i}>
                <div className="deadline" onClick={() => onBuilding(d.bldg)}>
                  <div className={`dl-days ${d.lvl}`}>
                    <div className="num">{d.days < 0 ? d.days : '+' + d.days}</div>
                    <div className="lab">{d.days < 0 ? 'overdue' : 'days'}</div>
                  </div>
                  <div className="dl-main">
                    <div className="t">{d.asset}</div>
                    <div className="m">{siteOf(d.bldg).short} · {siteOf(d.bldg).sp} · {d.meas}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                    <span className="chip neutral" style={{ color: d.lvl === 'urgent' ? '#f0938a' : d.lvl === 'warning' ? '#f0cd82' : 'var(--fg-2)' }}>
                      {d.exposure}
                    </span>
                    <div className="dl-bar"><i style={{ width: d.pct + '%', background: HEALTH[d.lvl === 'ok' ? 'resolved' : d.lvl] }} /></div>
                    {hasAi && (
                      <button className={`dl-chev ${isOpen ? 'open' : ''}`} aria-label="Toggle AI suggestion"
                        onClick={e => { e.stopPropagation(); toggleOne(i); }}>
                        <Icon name="chevron-down" />
                      </button>
                    )}
                  </div>
                </div>
                {hasAi && isOpen && (
                  <div className="dl-acc">
                    <AiStrip tip={d.ai} />
                  </div>
                )}
              </div>
              );
            })}
          </div>
        </div>

        <div className="stack">
          <div className="card" style={{ borderColor: 'rgba(91,155,240,.3)' }}>
            <div className="card-h">
              <h3 style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="sparkles" />Opsmera AI</h3>
              <span className="more" onClick={() => onNav('assistant')}>7 suggestions <Icon name="arrow-right" /></span>
            </div>
            <div style={{ padding: '4px 0' }}>
              <div className="mini-row" onClick={() => onNav('assistant')}>
                <div className="chan" style={{ background: 'var(--tint-urgent)', borderColor: 'transparent', color: '#f0938a' }}><Icon name="shield-alert" /></div>
                <div className="tx"><div className="s">Clear the Adelaide Central lighting breach today</div><div className="b">$4,000/wk exposure · cert blocks INV-20412</div></div>
              </div>
              <div className="mini-row" onClick={() => onNav('assistant')}>
                <div className="chan" style={{ background: 'var(--tint-warning)', borderColor: 'transparent', color: '#f0cd82' }}><Icon name="receipt" /></div>
                <div className="tx"><div className="s">Two invoices are one tap from Friday's run</div><div className="b">INV-20415 + INV-20418 · $5,600</div></div>
              </div>
              <div className="mini-row" onClick={() => onNav('assistant')}>
                <div className="chan" style={{ background: 'var(--tint-violet)', borderColor: 'transparent', color: '#c3b9f7' }}><Icon name="activity" /></div>
                <div className="tx"><div className="s">Pre-empt the Cove HVAC failure</div><div className="b">87% confidence · 30 days · add 2nd quote</div></div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-h">
              <h3>Latest intake</h3>
              <span className="more" onClick={() => onNav('intake')}>All 34 <Icon name="arrow-right" /></span>
            </div>
            {SCOPED_INTAKE.slice(0, 5).map(it => (
              <div className="mini-row" key={it.id} onClick={() => onNav('intake')}>
                <div className="chan"><Icon name={it.chan} /></div>
                <div className="tx">
                  <div className="s">{it.summ}</div>
                  <div className="b">{siteOf(it.bldg).short} · {siteOf(it.bldg).sp} · {it.channel}</div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
                  <span className="tm">{it.time}</span>
                  <TagFromStatus status={it.statusLabel} />
                </div>
              </div>
            ))}
          </div>

          <div className="card field-card">
            <div className="ph"><Icon name="mic" /></div>
            <div style={{ flex: 1 }}>
              <h4>Capture from the field</h4>
              <p>Building managers and trades log work by voice in 20 seconds, with photo evidence, from the site.</p>
            </div>
            <button className="btn btn-primary btn-sm" onClick={() => onNav('field')}>Open</button>
          </div>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { Dashboard });
