// Spreadsheet
function ModuleSheets() {
  const [tab, setTab] = React.useState('Home');
  const [selected, setSelected] = React.useState({r: 3, c: 5});
  const tabs = ['File', 'Home', 'Insert', 'Data', 'Formulas', 'Review', 'View', 'AI Assist'];
  const B = KS_DATA.budget;

  // 26 cols A-Z, 40 rows
  const cols = Array.from({length: 8}, (_, i) => String.fromCharCode(65 + i));
  const rows = 24;

  // Data lookup
  const cellData = (r, c) => {
    if (r === 0) {
      const heads = ['Department / Programme', 'Allocated (₹ Cr)', 'Utilised (₹ Cr)', 'Remaining (₹ Cr)', '% Utilised', 'Trend', 'Status', 'AI Insight'];
      return { v: heads[c] || '', header: true };
    }
    const row = B.rows[r - 1];
    if (!row) return { v: '' };
    if (c === 0) return { v: row[0], bold: true };
    if (c === 1) return { v: row[1].toLocaleString('en-IN'), num: true };
    if (c === 2) return { v: row[2].toLocaleString('en-IN'), num: true };
    if (c === 3) return { v: row[3].toLocaleString('en-IN'), num: true };
    if (c === 4) return { v: row[4].toFixed(1) + '%', num: true, heat: row[4] };
    if (c === 5) return { v: null, spark: true, val: row[4] };
    if (c === 6) return { v: row[4] > 70 ? 'On track' : row[4] > 55 ? 'Watch' : 'At risk', pill: row[4] > 70 ? 'ok' : row[4] > 55 ? 'warn' : 'err' };
    if (c === 7) return { v: null, ai: true, i: r - 1 };
    return { v: '' };
  };

  const aiInsight = (i) => ({
    0: 'Below 62% at mid-year — flag',
    1: 'Steady, aligns with S-curve',
    2: 'Cyber budget skewing to Q4',
    3: 'R&D under-utilised, reallocate?',
    4: 'On plan',
    5: 'Ahead of curve',
    6: 'Trending high, expect closeout',
    7: 'Watch — SLA-linked spend',
    8: 'Slow start, staffing gap',
    9: 'Nominal',
  }[i] || '');

  const selectedCell = cellData(selected.r, selected.c);
  const selectedAddr = cols[selected.c] + (selected.r + 1);

  return (
    <div className="ks-module"
         style={{'--mod-current':'var(--mod-sheets)', '--mod-current-tint':'var(--mod-sheets-tint)'}}
         data-screen-label="sheets">
      {/* Doc bar */}
      <div style={{
        padding: '8px 16px',
        background:'var(--white)',
        borderBottom:'1px solid var(--ink-150)',
        display:'flex', alignItems:'center', gap:12,
      }}>
        <div style={{
          width:28, height:28, borderRadius:6,
          background: 'var(--mod-sheets)', color:'white',
          display:'grid', placeItems:'center', fontWeight:700, fontSize:12,
        }}>S</div>
        <div className="col" style={{lineHeight:1.2}}>
          <div style={{fontWeight:600, fontSize:13.5}}>FY 2026-27 Budget Estimates — Consolidated</div>
          <div className="muted text-xs">MeitY / Finance · v22 · <span style={{color:'var(--ok)'}}>Approved by JS-Fin</span></div>
        </div>
        <div className="grow"/>
        <div className="row gap-2">
          {['SI','PR'].map((i, idx) => (
            <div key={i} style={{
              width:24, height:24, borderRadius:999,
              background:['#B45309','#0B4C8C'][idx],
              color:'white', fontSize:10, fontWeight:600,
              display:'grid', placeItems:'center',
              border:'2px solid var(--white)',
              marginLeft: idx === 0 ? 0 : -8,
              boxShadow: '0 0 0 1px var(--ink-200)',
            }}>{i}</div>
          ))}
          <button className="btn">{IC.comment} 2</button>
          <button className="btn">{IC.download}</button>
          <button className="btn primary">{IC.share} Share</button>
        </div>
      </div>

      <div className="ks-ribbon">
        <div className="ks-ribbon-tabs">
          {tabs.map(t => (
            <button key={t} className={"ks-ribbon-tab " + (tab === t ? 'active' : '')}
                    onClick={() => setTab(t)}>{t}</button>
          ))}
        </div>
        <div className="ks-ribbon-body">
          <div className="ks-ribbon-group">
            <div className="rb-select">Inter</div>
            <div className="rb-select" style={{minWidth:60}}>12</div>
          </div>
          <div className="ks-ribbon-group">
            <button className="rb-btn">{IC.bold}</button>
            <button className="rb-btn">{IC.italic}</button>
            <button className="rb-btn"><div className="rb-swatch" style={{background:'#FEF3C7'}}/></button>
          </div>
          <div className="ks-ribbon-group">
            <button className="rb-btn">₹</button>
            <button className="rb-btn">%</button>
            <button className="rb-btn">.00</button>
            <button className="rb-btn">1,000</button>
          </div>
          <div className="ks-ribbon-group">
            <button className="rb-btn">{IC.table} Pivot</button>
            <button className="rb-btn">{IC.chart} Chart</button>
            <button className="rb-btn">{IC.filter} Filter</button>
            <button className="rb-btn">{IC.sort} Sort</button>
          </div>
          <div className="ks-ribbon-group">
            <button className="rb-btn active">Conditional format</button>
            <button className="rb-btn">Data validation</button>
          </div>
          <div className="grow"/>
          <button className="btn ai">{IC.formula} AI Formula</button>
        </div>
      </div>

      {/* Formula bar */}
      <div style={{
        display:'flex', alignItems:'center', gap:8,
        padding:'6px 12px',
        background:'var(--white)',
        borderBottom:'1px solid var(--ink-150)',
      }}>
        <div style={{
          width:60, textAlign:'center',
          fontFamily:'var(--f-mono)', fontSize:12,
          padding:'4px 6px',
          border:'1px solid var(--ink-200)', borderRadius:5,
          background:'var(--ink-50)',
          fontWeight:600,
        }}>{selectedAddr}</div>
        <span style={{color:'var(--mod-sheets)', fontFamily:'var(--f-mono)', fontWeight:700, fontSize:15}}>ƒx</span>
        <div style={{
          flex:1,
          padding:'4px 8px',
          border:'1px solid var(--ink-200)', borderRadius:5,
          fontFamily:'var(--f-mono)', fontSize:12.5,
          background:'var(--white)',
        }}>
          {selected.c === 4 && selected.r > 0
            ? '=ROUND(C' + (selected.r + 1) + '/B' + (selected.r + 1) + '*100, 1)'
            : selectedCell?.v || ''}
        </div>
      </div>

      {/* Grid */}
      <div style={{flex:1, overflow:'auto', background:'var(--white)'}}>
        <table style={{borderCollapse:'collapse', fontSize:12.5, width:'100%', minWidth: 1100}}>
          <thead style={{position:'sticky', top:0, zIndex:5}}>
            <tr>
              <th style={{
                width: 44,
                background:'var(--ink-100)',
                border:'1px solid var(--ink-200)',
                borderTop:'none', borderLeft:'none',
              }}/>
              {cols.map((c, ci) => (
                <th key={c} style={{
                  background: ci === selected.c ? 'var(--mod-sheets-tint)' : 'var(--ink-100)',
                  color: ci === selected.c ? 'var(--mod-sheets)' : 'var(--ink-600)',
                  fontWeight: 600, fontSize: 11.5,
                  padding: '5px 8px',
                  border: '1px solid var(--ink-200)',
                  borderTop: 'none',
                  minWidth: ci === 0 ? 240 : (ci === 7 ? 220 : 110),
                  textAlign: 'center',
                }}>{c}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {Array.from({length: rows}, (_, r) => (
              <tr key={r}>
                <td style={{
                  background: r === selected.r ? 'var(--mod-sheets-tint)' : 'var(--ink-100)',
                  color: r === selected.r ? 'var(--mod-sheets)' : 'var(--ink-600)',
                  fontWeight: 600, fontSize: 11.5,
                  padding: '3px 6px',
                  border: '1px solid var(--ink-200)',
                  borderLeft: 'none',
                  textAlign: 'center',
                  height: 26,
                }}>{r + 1}</td>
                {cols.map((_, c) => {
                  const cd = cellData(r, c);
                  const isSel = r === selected.r && c === selected.c;
                  const bg = cd.header ? '#F5F7FA'
                    : (cd.heat !== undefined ? (
                        cd.heat > 70 ? '#E7F3EC' :
                        cd.heat > 55 ? '#FBF1E1' :
                        cd.heat > 0 ? '#FBEAEA' : undefined
                      ) : undefined);
                  return (
                    <td key={c}
                        onClick={() => setSelected({r, c})}
                        style={{
                          border: isSel ? '2px solid var(--mod-sheets)' : '1px solid var(--ink-200)',
                          padding: cd.spark ? 0 : '4px 8px',
                          background: bg,
                          fontWeight: cd.header ? 600 : (cd.bold ? 550 : 400),
                          fontFamily: cd.num ? 'var(--f-mono)' : 'inherit',
                          textAlign: cd.num ? 'right' : 'left',
                          color: cd.header ? 'var(--ink-700)' : (cd.ai ? 'var(--mod-ai)' : 'var(--ink-800)'),
                          fontSize: cd.header ? 11 : 12.5,
                          textTransform: cd.header ? 'uppercase' : 'none',
                          letterSpacing: cd.header ? '0.04em' : 'normal',
                          cursor: 'cell',
                          height: 26,
                          verticalAlign: 'middle',
                        }}>
                      {cd.spark && cd.val !== undefined ? (
                        <div style={{padding:'4px 8px', display:'flex', alignItems:'center', gap:6}}>
                          <div style={{flex:1, height:12, background:'var(--ink-100)', borderRadius:2, overflow:'hidden', position:'relative'}}>
                            <div style={{
                              position:'absolute', left:0, top:0, bottom:0,
                              width: cd.val + '%',
                              background: cd.val > 70 ? 'var(--ok)' : cd.val > 55 ? 'var(--warn)' : 'var(--err)',
                            }}/>
                          </div>
                        </div>
                      ) : cd.pill ? (
                        <span className={"chip " + cd.pill} style={{fontSize:10.5, padding:'1px 8px'}}>{cd.v}</span>
                      ) : cd.ai ? (
                        <span className="row gap-2" style={{fontSize:11.5}}>
                          <span style={{opacity:0.8}}>{IC.sparkles}</span>
                          <span style={{fontStyle:'italic'}}>{aiInsight(cd.i)}</span>
                        </span>
                      ) : cd.v}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Sheet tabs */}
      <div style={{
        display:'flex', alignItems:'center', gap:0,
        padding:'6px 8px 0',
        background:'var(--white)',
        borderTop:'1px solid var(--ink-150)',
      }}>
        {['Consolidated', 'Digital India', 'Cyber Security', 'R&D', 'CSC', 'Pivot: Utilisation', 'Charts'].map((s, i) => (
          <button key={s} style={{
            padding: '5px 12px',
            fontSize: 12,
            fontWeight: i === 0 ? 600 : 500,
            color: i === 0 ? 'var(--mod-sheets)' : 'var(--ink-600)',
            border:'none',
            borderBottom: i === 0 ? '2px solid var(--mod-sheets)' : '2px solid transparent',
            background:'transparent',
          }}>{s}</button>
        ))}
        <button className="ks-icon-btn" style={{height:24}}>{IC.plus}</button>
        <div className="grow"/>
        <div style={{fontSize:11.5, color:'var(--ink-600)', padding:'0 12px'}}>
          Sum: <b>91,680</b> · Avg: <b>4,584.0</b> · Count: <b>20</b>
        </div>
      </div>
    </div>
  );
}

window.ModuleSheets = ModuleSheets;
