// Excel / Spreadsheet + AI — the hero of this round.
// Native spreadsheet view inside Contro, with AI actively reading and
// editing cells live. Animated loop showing: planning → reading (row
// highlights sweep) → writing (cells flip to new values with diff pills)
// → summary.

function ExcelAIPage() {
  // Phase loop: 0 plan, 1 reading, 2 writing, 3 summary
  const [phase, setPhase] = React.useState(0);
  const [readRow, setReadRow] = React.useState(-1); // row index being read
  const [written, setWritten] = React.useState(new Set()); // row idx -> written
  const [thoughts, setThoughts] = React.useState([]);

  // Data model — a realistic cost-tracking sheet
  const sheet = React.useMemo(() => ({
    title: 'Harborview — cost tracking.xlsx',
    path: 'Projects / Harborview / Financials',
    tabs: ['Summary', 'Labor', 'Materials', 'Equipment', 'Subcontract'],
    activeTab: 'Materials',
    cols: ['SKU','Material','Qty','Unit','Unit $','Planned','Actual','Variance','Vendor','Updated'],
    colWidths: [62, 180, 58, 50, 62, 78, 78, 70, 110, 78],
    rows: [
      { c: ['SB-050','Rebar #5, 60ksi','48','ton','—','$41,280','$44,120','—','Atlantic Steel','Apr 18'],
        edit: { 4: '$860', 7: '+6.9%', 9: 'Apr 21' }, note: 'Looked up live spot price; actual invoice above plan' },
      { c: ['CM-040','Type IL cement','480','bag','$9.40','$4,512','$4,512','0.0%','Brannigan','Apr 12'] },
      { c: ['LM-210','2×10 SPF #2 KD','240','ea','$18.20','$4,368','$4,040','−7.5%','Pine Ridge','Apr 15'] },
      { c: ['IN-015','Mineral wool R-23','64','bdl','$74.10','$4,742','—','—','Rockwool NE','Apr 10'],
        edit: { 6: '$4,742', 7: '0.0%', 9: 'Apr 21' }, note: 'Pulled from receipt PDF · 64/64 received' },
      { c: ['GL-220','Low-E IGU 4×6','28','unit','$612','—','—','—','Clearline','—'],
        edit: { 5: '$17,136', 7: 'pending', 9: 'Apr 21' }, note: 'Quote attached to CO-017 · owner approved Tue' },
      { c: ['EL-110','MC cable 12/2','1,500','ft','$1.14','$1,710','$1,710','0.0%','Atlas Elec.','Apr 14'] },
      { c: ['PL-330','PEX-A 3/4"','800','ft','$2.10','$1,680','$1,680','0.0%','Uponor','Apr 11'] },
      { c: ['HD-092','Anchor bolt 5/8','120','ea','$4.80','$576','$588','+2.1%','Simpson','Apr 16'] },
      { c: ['FN-410','Finish tile matte','1,800','sqft','$6.40','$11,520','—','—','—','—'],
        edit: { 8: 'Meridian Tile', 9: 'Apr 21' }, note: 'Found 3 quotes — cheapest w/ approved spec' },
      { c: ['MB-050','TPO roof 60mil','4,200','sqft','$3.80','$15,960','—','—','Northern','Apr 19'] },
      { c: ['DW-120','Drywall 5/8" Type X','2,100','sheet','$18.90','$39,690','$13,608','−65.7%','USG','Apr 20'],
        edit: { 7: '−65.7%', 9: 'Apr 21' }, note: 'Partial receipt — flag remaining 1,380 sheets' },
    ],
  }), []);

  // Which rows the AI is "editing" this pass
  const editRows = React.useMemo(
    () => sheet.rows.map((r, i) => r.edit ? i : -1).filter(i => i >= 0),
    [sheet.rows]
  );

  // Drive the loop
  React.useEffect(() => {
    let t;
    const schedule = (ms, fn) => { t = setTimeout(fn, ms); };

    if (phase === 0) {
      setThoughts(['Opening sheet', 'Indexing columns A–J', 'Matching receipts + quotes']);
      schedule(1600, () => setPhase(1));
    } else if (phase === 1) {
      setThoughts((th) => [...th, 'Scanning 11 rows for missing actuals']);
      let i = 0;
      const step = () => {
        setReadRow(i);
        i++;
        if (i < sheet.rows.length) t = setTimeout(step, 160);
        else t = setTimeout(() => { setReadRow(-1); setPhase(2); }, 450);
      };
      step();
    } else if (phase === 2) {
      setThoughts((th) => [...th, `Writing ${editRows.length} updates to cells`]);
      let i = 0;
      const step = () => {
        const idx = editRows[i];
        setWritten((s) => new Set([...s, idx]));
        i++;
        if (i < editRows.length) t = setTimeout(step, 420);
        else t = setTimeout(() => setPhase(3), 900);
      };
      step();
    } else if (phase === 3) {
      setThoughts((th) => [...th, 'Done · 6 updates ready to review']);
      schedule(3200, () => {
        setThoughts([]); setWritten(new Set()); setPhase(0);
      });
    }
    return () => clearTimeout(t);
  }, [phase, editRows, sheet.rows.length]);

  return (
    <div style={{
      width: '100%', height: '100%', background: C.bg, color: C.ink,
      fontFamily: C.sans, fontSize: 13, letterSpacing: '-0.005em',
      display: 'grid', gridTemplateColumns: '220px 1fr 340px',
    }}>
      <CSidebar active="Documents" />

      {/* Center — sheet */}
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', background: C.panel }}>
        <ExcelFileHeader sheet={sheet} phase={phase} />
        <ExcelToolbar />
        <ExcelTabs tabs={sheet.tabs} active={sheet.activeTab} />
        <ExcelFormulaBar phase={phase} readRow={readRow} writtenCount={written.size} />
        <ExcelGrid
          sheet={sheet}
          readRow={readRow}
          written={written}
          phase={phase}
        />
        <ExcelStatusBar phase={phase} />
      </div>

      {/* Right — AI panel */}
      <AIPanel phase={phase} thoughts={thoughts} edits={editRows.length} sheet={sheet} written={written} />
    </div>
  );
}

function ExcelFileHeader({ sheet, phase }) {
  const saving = phase === 2;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px',
      borderBottom: `1px solid ${C.line}`, background: C.bg,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 4,
        background: '#107c41', color: '#fff',
        display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700,
        fontFamily: C.mono,
      }}>X</div>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontWeight: 600, fontSize: 13 }}>{sheet.title}</span>
          <span style={{ fontSize: 11, color: C.ink3 }}>· {sheet.path}</span>
        </div>
        <div style={{ fontSize: 11, color: C.ink3, marginTop: 1 }}>
          Linked to OneDrive · Two-way sync · Last edited by you 2m ago
        </div>
      </div>

      {/* Presence / saving status */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        fontSize: 11, color: saving ? C.blue : C.mint, fontWeight: 500,
      }}>
        <span style={{
          width: 6, height: 6, borderRadius: '50%',
          background: saving ? C.blue : C.mint,
          animation: saving ? 'pulse 1.2s ease-in-out infinite' : 'none',
        }} />
        {saving ? 'Saving to Excel…' : 'Saved'}
      </div>
      <div style={{ display: 'flex', marginLeft: 8 }}>
        <PresenceDot c="#cbb79a" label="MR" />
        <PresenceDot c="#8da8c4" label="JI" off={-6} />
        <div style={{
          width: 22, height: 22, borderRadius: '50%', background: `linear-gradient(135deg, ${C.blue}, ${C.indigo})`,
          color: '#fff', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 600,
          marginLeft: -6, fontFamily: C.mono, border: '2px solid #fff',
        }}>C</div>
      </div>
      <CButton icon="↗">Share</CButton>
    </div>
  );
}

function PresenceDot({ c, label, off }) {
  return (
    <div style={{
      width: 22, height: 22, borderRadius: '50%', background: c, color: C.ink,
      display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 600,
      marginLeft: off || 0, border: '2px solid #fff',
    }}>{label}</div>
  );
}

function ExcelToolbar() {
  // Simplified ribbon
  const tools = ['▤ File','▦ Home','▫ Insert','Σ Formulas','◧ Data','⎋ Review','⌕ View'];
  return (
    <div style={{ display: 'flex', gap: 20, padding: '6px 18px', fontSize: 11, color: C.ink2, borderBottom: `1px solid ${C.line2}`, background: C.panel }}>
      {tools.map((t, i) => (
        <span key={t} style={{ color: i === 1 ? C.ink : C.ink3, fontWeight: i === 1 ? 500 : 400 }}>{t}</span>
      ))}
      <span style={{ marginLeft: 'auto', fontSize: 11, color: C.ink3, fontFamily: C.mono }}>
        Calibri · 11 · $ · % · ,
      </span>
    </div>
  );
}

function ExcelTabs({ tabs, active }) {
  return (
    <div style={{ display: 'flex', gap: 2, padding: '0 10px', borderBottom: `1px solid ${C.line}`, background: C.bg }}>
      {tabs.map((t) => (
        <div key={t} style={{
          padding: '6px 14px', fontSize: 11, fontWeight: t === active ? 500 : 400,
          color: t === active ? C.ink : C.ink2,
          background: t === active ? C.panel : 'transparent',
          border: t === active ? `1px solid ${C.line}` : '1px solid transparent',
          borderBottom: t === active ? `1px solid ${C.panel}` : 'none',
          borderRadius: '6px 6px 0 0', marginBottom: -1,
        }}>{t}</div>
      ))}
    </div>
  );
}

function ExcelFormulaBar({ phase, readRow, writtenCount }) {
  let cellRef = 'A1';
  let formula = '';
  if (phase === 1 && readRow >= 0) {
    cellRef = `A${readRow + 2}:J${readRow + 2}`;
    formula = '= READING ROW';
  } else if (phase === 2) {
    cellRef = `H${writtenCount + 2}`;
    formula = '= ACTUAL / PLANNED - 1';
  } else if (phase === 3) {
    cellRef = 'SUMMARY';
    formula = '6 edits applied · awaiting review';
  } else {
    cellRef = 'A1';
    formula = 'Harborview — cost tracking';
  }
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '6px 12px',
      borderBottom: `1px solid ${C.line}`, background: C.panel,
      fontFamily: C.mono, fontSize: 11,
    }}>
      <span style={{
        padding: '3px 8px', border: `1px solid ${C.line}`, borderRadius: 4,
        minWidth: 80, textAlign: 'center', color: C.ink,
      }}>{cellRef}</span>
      <span style={{ color: C.ink3 }}>fx</span>
      <span style={{ color: phase === 2 ? C.blue : C.ink2 }}>{formula}</span>
      {phase === 1 && (
        <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6, color: C.blue }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: C.blue, animation: 'pulse 0.8s ease-in-out infinite' }} />
          Contro is reading
        </span>
      )}
      {phase === 2 && (
        <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6, color: C.blue }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: C.blue, animation: 'pulse 0.6s ease-in-out infinite' }} />
          Contro is writing · {writtenCount} of 6
        </span>
      )}
    </div>
  );
}

function ExcelGrid({ sheet, readRow, written, phase }) {
  return (
    <div style={{ flex: 1, overflow: 'hidden', background: C.panel, position: 'relative' }}>
      {/* Column headers */}
      <div style={{ display: 'flex', borderBottom: `1px solid ${C.line}`, background: C.bg }}>
        <div style={{
          width: 34, height: 22, display: 'grid', placeItems: 'center',
          fontSize: 10, color: C.ink3, borderRight: `1px solid ${C.line}`,
        }}>◢</div>
        {sheet.cols.map((col, i) => (
          <div key={col} style={{
            width: sheet.colWidths[i], height: 22, padding: '0 8px',
            display: 'flex', alignItems: 'center',
            fontSize: 10, color: C.ink3, fontWeight: 500,
            borderRight: `1px solid ${C.line}`,
            fontFamily: C.mono,
          }}>
            <span style={{ color: C.ink4, marginRight: 6 }}>{String.fromCharCode(65 + i)}</span>
            {col}
          </div>
        ))}
      </div>

      {/* Rows */}
      {sheet.rows.map((r, ri) => {
        const reading = readRow === ri;
        const isWritten = written.has(ri);
        const wasEdit = Boolean(r.edit);
        return (
          <div key={ri} style={{
            display: 'flex', height: 26, position: 'relative',
            background: reading ? 'rgba(37,99,235,0.06)' : 'transparent',
            borderBottom: `1px solid ${C.line2}`,
            transition: 'background 200ms',
          }}>
            {/* Row number */}
            <div style={{
              width: 34, display: 'grid', placeItems: 'center',
              fontSize: 10, color: C.ink3, background: C.bg,
              borderRight: `1px solid ${C.line}`,
            }}>{ri + 2}</div>

            {/* Cells */}
            {r.c.map((val, ci) => {
              const edited = wasEdit && r.edit[ci] != null && isWritten;
              const shown = edited ? r.edit[ci] : val;
              const isNum = /^(\$|−|\+|\d)/.test(String(shown)) || /%$/.test(String(shown));
              return (
                <div key={ci} style={{
                  width: sheet.colWidths[ci], padding: '0 8px',
                  display: 'flex', alignItems: 'center',
                  borderRight: `1px solid ${C.line2}`,
                  fontSize: 11, fontFamily: isNum ? C.mono : C.sans,
                  color: shown === '—' ? C.ink4 : C.ink,
                  background: edited ? 'rgba(37,99,235,0.10)' : 'transparent',
                  position: 'relative',
                  transition: 'background 400ms',
                  overflow: 'hidden', whiteSpace: 'nowrap',
                  fontWeight: edited ? 600 : 400,
                }}>
                  {shown}
                  {edited && (
                    <span style={{
                      position: 'absolute', right: 2, top: 1, bottom: 1,
                      width: 2, background: C.blue, borderRadius: 1,
                      animation: 'blink 1s steps(2) infinite',
                    }} />
                  )}
                </div>
              );
            })}

            {/* Reading highlight — scanning bar */}
            {reading && (
              <div style={{
                position: 'absolute', left: 34, right: 0, top: 0, bottom: 0,
                pointerEvents: 'none',
                border: `1px solid ${C.blue}`,
                boxShadow: '0 0 0 3px rgba(37,99,235,0.12) inset',
              }} />
            )}
          </div>
        );
      })}

      {/* Footer totals */}
      <div style={{ display: 'flex', height: 26, borderTop: `1px solid ${C.line}`, background: C.line2 }}>
        <div style={{ width: 34, background: C.bg, borderRight: `1px solid ${C.line}` }}></div>
        <div style={{ width: sheet.colWidths[0], padding: '0 8px', display: 'flex', alignItems: 'center', fontSize: 11, fontFamily: C.mono, color: C.ink3, borderRight: `1px solid ${C.line2}` }}>
          TOTAL
        </div>
        <div style={{ width: sheet.colWidths[1], borderRight: `1px solid ${C.line2}` }}></div>
        <div style={{ width: sheet.colWidths[2], borderRight: `1px solid ${C.line2}` }}></div>
        <div style={{ width: sheet.colWidths[3], borderRight: `1px solid ${C.line2}` }}></div>
        <div style={{ width: sheet.colWidths[4], borderRight: `1px solid ${C.line2}` }}></div>
        <div style={{ width: sheet.colWidths[5], padding: '0 8px', display: 'flex', alignItems: 'center', fontSize: 11, fontFamily: C.mono, color: C.ink, borderRight: `1px solid ${C.line2}`, fontWeight: 600 }}>
          $143,174
        </div>
        <div style={{ width: sheet.colWidths[6], padding: '0 8px', display: 'flex', alignItems: 'center', fontSize: 11, fontFamily: C.mono, color: C.ink, borderRight: `1px solid ${C.line2}`, fontWeight: 600 }}>
          $70,258
        </div>
        <div style={{ width: sheet.colWidths[7], padding: '0 8px', display: 'flex', alignItems: 'center', fontSize: 11, fontFamily: C.mono, color: C.amber, borderRight: `1px solid ${C.line2}`, fontWeight: 600 }}>
          −51.0%
        </div>
      </div>
    </div>
  );
}

function ExcelStatusBar({ phase }) {
  const label = ['Ready','Reading 11 rows','Writing edits','6 edits · awaiting review'][phase];
  return (
    <div style={{
      height: 22, borderTop: `1px solid ${C.line}`, background: C.bg,
      display: 'flex', alignItems: 'center', gap: 18, padding: '0 14px',
      fontSize: 10, color: C.ink3, fontFamily: C.mono,
    }}>
      <span>{label}</span>
      <span>·</span>
      <span>Sheet1 of 5</span>
      <span style={{ marginLeft: 'auto' }}>Σ sum 70,258 · avg 8,782 · count 11</span>
      <span>100%</span>
    </div>
  );
}

// ── AI panel ──────────────────────────────────────────────────
function AIPanel({ phase, thoughts, edits, sheet, written }) {
  return (
    <div style={{
      background: C.panel, borderLeft: `1px solid ${C.line}`,
      display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${C.line}`, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 26, height: 26, borderRadius: 6,
          background: `linear-gradient(135deg, ${C.blue}, ${C.indigo})`,
          display: 'grid', placeItems: 'center', color: '#fff',
          fontFamily: C.mono, fontSize: 12, fontWeight: 600,
          position: 'relative',
        }}>
          C
          {(phase === 1 || phase === 2) && (
            <span style={{
              position: 'absolute', inset: -4, borderRadius: 10,
              border: `1.5px solid ${C.blue}`,
              animation: 'ping 1.4s ease-out infinite',
            }} />
          )}
        </div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Contro</div>
          <div style={{ fontSize: 11, color: C.ink3 }}>
            {phase === 0 && 'Planning update pass'}
            {phase === 1 && 'Reading your spreadsheet'}
            {phase === 2 && 'Editing cells'}
            {phase === 3 && 'Ready for review'}
          </div>
        </div>
      </div>

      {/* The user's instruction */}
      <div style={{ padding: '12px 18px', borderBottom: `1px solid ${C.line}`, background: C.bg }}>
        <div style={{ fontSize: 10, color: C.ink3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 500, marginBottom: 6 }}>
          You asked
        </div>
        <div style={{ fontSize: 13, lineHeight: 1.5, color: C.ink }}>
          Reconcile Harborview materials with today's receipts and the new Low-E quote. Fill missing actuals and flag overruns.
        </div>
      </div>

      {/* Thinking stream */}
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${C.line}` }}>
        <div style={{ fontSize: 10, color: C.ink3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 500, marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
          Thinking
          <span style={{ fontFamily: C.mono, background: C.line2, padding: '1px 5px', borderRadius: 3, color: C.ink2, letterSpacing: 'normal' }}>
            {thoughts.length}
          </span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {thoughts.map((t, i) => {
            const last = i === thoughts.length - 1;
            return (
              <div key={i} style={{
                display: 'flex', gap: 10, fontSize: 12, lineHeight: 1.45,
                color: last ? C.ink : C.ink2,
                opacity: last ? 1 : 0.7,
              }}>
                <span style={{
                  width: 6, height: 6, borderRadius: '50%',
                  background: last ? C.blue : C.ink4, marginTop: 7, flexShrink: 0,
                }} />
                <span>{t}{last && (phase === 1 || phase === 2) && (
                  <span style={{
                    display: 'inline-block', width: 2, height: 12,
                    background: C.blue, marginLeft: 2, verticalAlign: 'text-bottom',
                    animation: 'blink 1s steps(2) infinite',
                  }} />
                )}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Edits list / diff review */}
      <div style={{ flex: 1, overflow: 'auto', padding: '14px 18px' }}>
        <div style={{ fontSize: 10, color: C.ink3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 500, marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
          Proposed edits
          <span style={{ fontFamily: C.mono, background: C.line2, padding: '1px 5px', borderRadius: 3, color: C.ink2, letterSpacing: 'normal' }}>
            {edits}
          </span>
          {phase === 3 && <span style={{ marginLeft: 'auto', color: C.mint, letterSpacing: 'normal' }}>ready</span>}
        </div>

        {sheet.rows.map((r, ri) => {
          if (!r.edit) return null;
          const applied = written.has(ri);
          return (
            <div key={ri} style={{
              padding: 10, border: `1px solid ${C.line}`, borderRadius: 7,
              marginBottom: 8, fontSize: 11,
              background: applied ? C.blueSoft : C.bg,
              opacity: applied ? 1 : 0.65,
              transition: 'all 400ms',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                <span style={{ fontFamily: C.mono, color: C.ink2, fontSize: 10 }}>row {ri + 2}</span>
                <span style={{ fontWeight: 500, fontSize: 11 }}>{r.c[1]}</span>
                <span style={{ marginLeft: 'auto', fontSize: 10, color: applied ? C.blue : C.ink3 }}>
                  {applied ? '● written' : '○ queued'}
                </span>
              </div>
              <div style={{ fontSize: 11, color: C.ink2, lineHeight: 1.5, marginBottom: 6 }}>
                {r.note}
              </div>
              <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                {Object.entries(r.edit).map(([ci, v]) => (
                  <span key={ci} style={{
                    fontFamily: C.mono, fontSize: 10,
                    padding: '2px 6px', background: '#fff',
                    border: `1px solid ${applied ? C.blue : C.line}`,
                    color: applied ? C.blueDeep : C.ink2, borderRadius: 3,
                  }}>
                    {String.fromCharCode(65 + Number(ci))}: {v}
                  </span>
                ))}
              </div>
            </div>
          );
        })}

        {phase === 3 && (
          <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
            <CButton primary icon="✓">Accept all</CButton>
            <CButton>Review one by one</CButton>
          </div>
        )}
      </div>

      {/* Input */}
      <div style={{ padding: 14, borderTop: `1px solid ${C.line}`, background: C.bg }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
          background: C.panel, border: `1px solid ${C.line}`, borderRadius: 8,
          fontSize: 13, color: C.ink3,
        }}>
          <span>Ask about this sheet, or give an instruction…</span>
          <span style={{ marginLeft: 'auto', fontSize: 16 }}>↵</span>
        </div>
      </div>

      {/* animations */}
      <style>{`
        @keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.35 } }
        @keyframes blink { 50% { opacity: 0 } }
        @keyframes ping {
          0%   { transform: scale(1);   opacity: 0.7 }
          80%  { transform: scale(1.6); opacity: 0 }
          100% { transform: scale(1.6); opacity: 0 }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { ExcelAIPage });
