/* global React, EpisodeHeader, Watermark, DisclaimerFooter, Banner */
// P14 — Capstone Gate M04 · panel 6×4×3 (desktop) + vista por sector (móvil)

const { useState: useC } = React;

const SECTORS = ['Software', 'Industrial', 'Energy', 'Retail apparel', 'Banca', 'Healthcare'];
const MULTIPLES = ['P/E clean', 'EV/EBITDA', 'EV/Sales', 'P/B'];
const COMPANIES_BY_SECTOR = {
  'Software':       ['SAAS-A', 'SAAS-B', 'PLAT-C'],
  'Industrial':     ['INDU-A', 'MACH-B', 'AUTO-C'],
  'Energy':         ['OILG-A', 'GASR-B', 'RENW-C'],
  'Retail apparel': ['LUXR-A', 'PREM-B', 'MASS-C'],
  'Banca':          ['BANK-A', 'BANK-B', 'NEOB-C'],
  'Healthcare':     ['PHRM-A', 'MEDV-B', 'BIOT-C'],
};

// 72 cells of data
const buildPanel = () => {
  const panel = {};
  SECTORS.forEach((s, si) => {
    COMPANIES_BY_SECTOR[s].forEach((c, ci) => {
      MULTIPLES.forEach((m, mi) => {
        const key = `${s}|${c}|${m}`;
        // primary multiple by sector
        const primaryByCorr = {
          'Software': 'EV/Sales',
          'Industrial': 'EV/EBITDA',
          'Energy': 'EV/EBITDA',
          'Retail apparel': 'EV/EBITDA',
          'Banca': 'P/E clean',
          'Healthcare': 'EV/EBITDA',
        };
        const isPrimary = m === primaryByCorr[s];
        // fake values
        const base = (si + 1) * 3 + (ci + 1) * 1.5 + (mi + 1) * 0.8;
        panel[key] = {
          value: base + Math.sin(si*7 + ci*3 + mi) * 2.5,
          isPrimary,
          filled: (si * 12 + ci * 4 + mi) < 38, // 38/72 cells filled
          flagged: (si === 2 && c === 'OILG-A' && m === 'EV/EBITDA') || (si === 3 && c === 'LUXR-A' && m === 'P/E clean'),
        };
      });
    });
  });
  return panel;
};

const P14_Capstone = () => {
  const [panel] = useC(buildPanel);
  const [selected, setSelected] = useC(`Energy|OILG-A|EV/EBITDA`);
  const sel = panel[selected];
  const [sector, company, multiple] = selected.split('|');

  const filledCount = Object.values(panel).filter(c => c.filled).length;

  return (
    <div className="artboard-root">
      <EpisodeHeader
        breadcrumb="C04-A · M04 · E06 · CAPSTONE"
        title="Panel 6 × 4 × 3 — síntesis del curso"
        bigQuestion="¿Puedes defender un panel completo ante un comité, sin atajos lingüísticos?"
        durationDone={142}
        durationTotal={240}
      />

      <div style={{ maxWidth: 1500, margin: '0 auto', padding: '20px 28px' }}>
        {/* Top bar: progress */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, marginBottom: 20, alignItems: 'center' }}>
          <div>
            <div className="row" style={{ gap: 8, marginBottom: 8 }}>
              <span className="badge" style={{ borderColor: 'var(--signal-hypothesis)', color: 'var(--signal-hypothesis)' }}>GATE + PROJ · CAPSTONE</span>
              <span className="badge">6 sectores</span>
              <span className="badge">4 múltiplos</span>
              <span className="badge">3 empresas / sector</span>
              <span className="badge">72 celdas</span>
            </div>
            <div className="row" style={{ gap: 12 }}>
              <span className="txt-sm txt-sec">{filledCount} / 72 celdas con valor + drivers + fuente + limitación</span>
              <div style={{ width: 200 }}>
                <div className="rubric-bar"><div className="rubric-fill warn" style={{ width: `${(filledCount/72)*100}%` }}/></div>
              </div>
            </div>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <button className="btn">Vista por sector (móvil)</button>
            <button className="btn">Vista de revisión</button>
            <button className="btn btn-primary" disabled>Enviar a comité (38 / 72 incompletas)</button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 20 }}>
          {/* 6×4×3 panel */}
          <div className="card" style={{ padding: 0, overflow: 'auto', position: 'relative' }}>
            <table className="table" style={{ fontSize: 11, minWidth: 760 }}>
              <thead style={{ position: 'sticky', top: 0, background: 'var(--surface-1)', zIndex: 2 }}>
                <tr>
                  <th style={{ width: 130 }}>Sector / Empresa</th>
                  {MULTIPLES.map(m => <th key={m} className="num">{m}</th>)}
                  <th style={{ width: 70 }}>Veredicto</th>
                </tr>
              </thead>
              <tbody>
                {SECTORS.map((s) => (
                  <React.Fragment key={s}>
                    <tr style={{ background: 'var(--surface-2)' }}>
                      <td colSpan={6} style={{ padding: '6px 12px' }}>
                        <span className="mono" style={{ fontSize: 11, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{s}</span>
                      </td>
                    </tr>
                    {COMPANIES_BY_SECTOR[s].map(c => {
                      // sector verdict
                      const seed = (s.length + c.length) % 3;
                      const verdict = seed === 0 ? 'pass' : seed === 1 ? 'hypothesis' : 'warning';
                      return (
                        <tr key={`${s}-${c}`}>
                          <td className="mono" style={{ paddingLeft: 24 }}>{c}.MC</td>
                          {MULTIPLES.map(m => {
                            const key = `${s}|${c}|${m}`;
                            const cell = panel[key];
                            const isSel = key === selected;
                            return (
                              <td
                                key={m}
                                className="num"
                                onClick={() => setSelected(key)}
                                style={{
                                  cursor: 'pointer',
                                  background: isSel ? 'var(--accent-muted)' :
                                              cell.flagged ? 'var(--tint-warning)' :
                                              !cell.filled ? 'rgba(240,184,110,0.06)' : 'transparent',
                                  position: 'relative',
                                  fontWeight: cell.isPrimary ? 600 : 400,
                                  color: cell.isPrimary ? 'var(--signal-driver)' : cell.filled ? 'var(--text-primary)' : 'var(--text-tertiary)',
                                  borderLeft: isSel ? '2px solid var(--accent)' : 'none',
                                }}
                                title={`${c}.MC · ${m}`}
                              >
                                {cell.filled
                                  ? <>
                                      {cell.value.toFixed(1)}×
                                      {cell.isPrimary && <span style={{ marginLeft: 4, fontSize: 8, color: 'var(--accent)' }}>●</span>}
                                      {cell.flagged && <span style={{ marginLeft: 4, color: 'var(--signal-warning)' }}>⚠</span>}
                                    </>
                                  : <span style={{ color: 'var(--signal-hypothesis)' }}>—</span>
                                }
                              </td>
                            );
                          })}
                          <td>
                            <span className={`chip chip-${verdict}`} style={{ fontSize: 10 }}>
                              ● {verdict === 'pass' ? 'verde' : verdict === 'hypothesis' ? 'ámbar' : 'rojo'}
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
            <Watermark />
            <div style={{ height: 18 }}/>
          </div>

          {/* Selected cell editor */}
          <div className="col" style={{ gap: 14, position: 'sticky', top: 90, alignSelf: 'flex-start' }}>
            <div className="card" style={{ padding: 16 }}>
              <div className="row" style={{ marginBottom: 12, gap: 8 }}>
                <span className="badge">{sector}</span>
                <span className="mono bold txt-sm">{company}.MC</span>
                <span className="badge" style={{ borderColor: 'var(--accent)', color: 'var(--accent)' }}>{multiple}</span>
              </div>
              <div className="trio-card" style={{ background: 'var(--surface-2)' }}>
                <div className="txt-xs txt-ter mono" style={{ textTransform: 'uppercase' }}>Valor de la celda</div>
                <div className="trio-value">{sel.value.toFixed(1)}×</div>
                <div className="row" style={{ gap: 6, marginTop: 4 }}>
                  <span className="chip chip-driver">drivers · g, ROIC, intensidad K</span>
                </div>
              </div>

              <div style={{ marginTop: 14 }}>
                <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
                  <span className="txt-xs txt-ter mono" style={{ textTransform: 'uppercase' }}>¿Múltiplo primario en este sector?</span>
                  <span className={`chip ${sel.isPrimary ? 'chip-pass' : ''}`}>{sel.isPrimary ? '✓ sí' : 'secundario'}</span>
                </div>
                <div className="row" style={{ gap: 6 }}>
                  {MULTIPLES.map(m => (
                    <button key={m} className={`chip ${m === multiple ? 'chip-active' : ''}`} style={{ fontSize: 11 }}>{m}</button>
                  ))}
                </div>
              </div>

              <div className="divider"></div>

              <div className="col" style={{ gap: 10 }}>
                <div>
                  <div className="txt-xs txt-ter mono" style={{ textTransform: 'uppercase', marginBottom: 4 }}>Fuente</div>
                  <input className="input" defaultValue="dataset[OILG-A].ebitda_2024 / EV_calc.row[12]" />
                </div>
                <div>
                  <div className="txt-xs txt-ter mono" style={{ textTransform: 'uppercase', marginBottom: 4 }}>Limitación 1-línea <span style={{ color: 'var(--signal-warning)' }}>⚠</span></div>
                  <input className="input" style={{ color: 'var(--signal-hypothesis)' }} defaultValue="EBITDA en pico cíclico — normalizar mid-cycle (5y avg)" />
                </div>
                <div>
                  <div className="txt-xs txt-ter mono" style={{ textTransform: 'uppercase', marginBottom: 4 }}>Justificación</div>
                  <textarea
                    className="textarea"
                    style={{ minHeight: 100, fontSize: 'var(--size-sm)', fontFamily: 'var(--font-serif)' }}
                    defaultValue="EV/EBITDA 4,6× sobre EBITDA 2024 que coincide con pico cíclico del sector energy. Ajustado a mid-cycle 5y (-32% EBITDA medio), el múltiplo normalizado es ~6,8×, en línea con sector mediano 7,2×. No constituye señal de descuento estructural."
                  />
                </div>
              </div>

              <div className="divider"></div>

              <div className="row" style={{ gap: 8 }}>
                <button className="btn btn-ghost" style={{ flex: 1 }}>Anti-tesis falsable</button>
                <button className="btn btn-primary" style={{ flex: 1 }}>Marcar celda completa</button>
              </div>
            </div>

            <Banner
              tone="warning"
              icon="⚠"
              title="Linter del capstone"
              text='Detectado "barata" en tu memo de SAAS-A (sector Software). Reemplaza por "múltiplo aparente por debajo de sector".'
            />
          </div>
        </div>

        {/* Top 3 ideas + anti-tesis */}
        <div style={{ marginTop: 24 }}>
          <div className="row" style={{ marginBottom: 14 }}>
            <div className="txt-xs txt-ter mono" style={{ textTransform: 'uppercase' }}>Top 3 ideas con anti-tesis falsable</div>
            <span className="chip chip-pass" style={{ marginLeft: 12 }}>2 / 3 cerradas</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {[
              { idea: 'SAAS-A con EV/Sales 8,2× y margen objetivo implícito 30%', anti: 'Si margen operativo no supera 22% en 8 trimestres, el múltiplo asume crecimiento+expansión que no se materializa.', status: 'pass' },
              { idea: 'BANK-A con P/E clean 7,1× y ROE 14%, P/E_Gordon = 9,5×', anti: 'Si NPL ratio supera 4% sostenido 2 años, el P/E_clean es contable, no económico — el descuento desaparece.', status: 'pass' },
              { idea: 'PHRM-A · pendiente · pipeline 3 moléculas en fase III', anti: '— escribe anti-tesis aquí —', status: 'pending' },
            ].map((it, i) => (
              <div key={i} className="card" style={{ padding: 16, borderColor: it.status === 'pending' ? 'var(--signal-hypothesis)' : 'var(--border-default)', borderStyle: it.status === 'pending' ? 'dashed' : 'solid' }}>
                <div className="row" style={{ marginBottom: 8 }}>
                  <span className="badge">IDEA #{i+1}</span>
                  {it.status === 'pass' ? <span className="chip chip-pass" style={{ marginLeft: 'auto' }}>completa</span> : <span className="chip chip-hypothesis" style={{ marginLeft: 'auto' }}>pendiente</span>}
                </div>
                <div className="serif" style={{ fontSize: 'var(--size-md)', lineHeight: 1.5, marginBottom: 12 }}>
                  {it.idea}
                </div>
                <div style={{ padding: 10, background: 'var(--surface-2)', borderRadius: 'var(--r-md)', borderLeft: '3px solid var(--signal-warning)' }}>
                  <div className="txt-xs mono" style={{ color: 'var(--signal-warning)', textTransform: 'uppercase', marginBottom: 4 }}>Anti-tesis</div>
                  <div className="txt-sm" style={{ color: it.status === 'pending' ? 'var(--text-tertiary)' : 'var(--text-secondary)', lineHeight: 1.45 }}>{it.anti}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Mobile preview */}
        <div style={{ marginTop: 32, padding: 18, border: '1px dashed var(--border-default)', borderRadius: 'var(--r-lg)' }}>
          <div className="row" style={{ marginBottom: 14 }}>
            <span className="badge">VISTA MÓVIL · 1 SECTOR A LA VEZ</span>
            <span className="txt-xs txt-sec" style={{ marginLeft: 12 }}>Resuelve R4: 1 sector × 4 múltiplos × 3 empresas = 12 celdas + 1 panel de "primario"</span>
          </div>
          <div style={{ width: 360, margin: '0 auto', background: 'var(--surface-1)', border: '1px solid var(--border-default)', borderRadius: 18, padding: 12 }}>
            <div className="row" style={{ gap: 4, marginBottom: 12, overflowX: 'auto', padding: 2 }}>
              {SECTORS.map((s, i) => (
                <button key={s} className={`chip ${i === 2 ? 'chip-active' : ''}`} style={{ fontSize: 11, flexShrink: 0 }}>{s}</button>
              ))}
            </div>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
              <span className="bold">Energy</span>
              <span className="chip chip-hypothesis" style={{ fontSize: 10 }}>3 / 12 celdas</span>
            </div>
            <table className="table" style={{ fontSize: 10 }}>
              <thead><tr><th></th>{MULTIPLES.map(m => <th key={m} className="num" style={{ fontSize: 9 }}>{m.split(' ')[0]}</th>)}</tr></thead>
              <tbody>
                {COMPANIES_BY_SECTOR['Energy'].map(c => (
                  <tr key={c}>
                    <td className="mono" style={{ fontSize: 10 }}>{c}</td>
                    {MULTIPLES.map(m => {
                      const cell = panel[`Energy|${c}|${m}`];
                      return <td key={m} className="num" style={{ fontSize: 10, color: cell.isPrimary ? 'var(--signal-driver)' : 'var(--text-secondary)' }}>{cell.value.toFixed(1)}×</td>;
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <DisclaimerFooter expanded />
    </div>
  );
};

Object.assign(window, { P14_Capstone });
