// screens.jsx - pantallas principales de la app Giraudo

function FormulaSection({ result, state }) {
  const [open, setOpen] = React.useState(() => {
    try { return localStorage.getItem('giraudo_formula_open') !== '0'; } catch { return true; }
  });
  React.useEffect(() => {
    try { localStorage.setItem('giraudo_formula_open', open ? '1' : '0'); } catch {}
  }, [open]);
  const isPre = state.material === 'PREPINTADA';
  if (!result) return null;

  const a = parseFloat(state.ancho) || 0;
  const l = parseFloat(state.largo) || 0;
  const q = Math.max(1, parseInt(state.cantidad) || 1);
  const pl = result.planchaElegida;
  const ppp = result.piezasPorPlancha || 0;
  const planchas = result.unidad || 0;
  const precioPlancha = pl?.precio_plancha || 0;

  const rows = pl ? [
    {
      label: 'Plancha óptima',
      expr: `${pl.ancho} × ${pl.largo} mm · ${window.fmtMoney(precioPlancha)}/plancha`,
      value: `${pl.ancho}×${pl.largo}`,
    },
    {
      label: 'Piezas por plancha',
      expr: `pieza ${a}×${l} mm → ${ppp} piezas aprovechando la plancha`,
      value: `${ppp} piezas`,
    },
    {
      label: 'Planchas necesarias',
      expr: `⌈ ${q} piezas ÷ ${ppp} piezas/plancha ⌉`,
      value: `${planchas} ${planchas === 1 ? 'plancha' : 'planchas'}`,
    },
    {
      label: 'Costo base',
      expr: `${planchas} × ${window.fmtMoney(precioPlancha)}`,
      value: window.fmtMoney(result.costoBase),
    },
    {
      label: 'Costo neto',
      expr: `+ ${state.envio}% envío + ${state.desperdicio}% desperdicio`,
      value: window.fmtMoney(result.costoNeto),
    },
    {
      label: 'Precio final',
      expr: `× ${state.manoObra} mano de obra`,
      value: window.fmtMoney(result.precioFinal),
      highlight: true,
    },
  ] : [
    {
      label: 'Sin datos',
      expr: a > 0 && l > 0 ? 'La pieza no entra en ninguna plancha disponible' : 'Ingresá ancho y largo del desarrollo',
      value: '—',
    },
  ];

  return (
    <div style={{
      border: '2px solid var(--fg)', borderRadius: 4,
      background: 'var(--accent-soft)',
      flexShrink: 0, minHeight: 'max-content',
    }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: '100%', padding: '14px 18px',
        background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        gap: 12,
      }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
            color: 'var(--accent)', letterSpacing: '0.18em', textTransform: 'uppercase',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ fontSize: 12 }}>{open ? '▾' : '▸'}</span> Fórmula Aplicada
          </div>
          {result.planchaElegida ? (
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)',
              fontWeight: 600, marginTop: 4, letterSpacing: '0.04em', lineHeight: 1.5,
            }}>
              <span style={{ color: 'var(--fg)', fontWeight: 800 }}>
                {result.planchaElegida.ancho}×{result.planchaElegida.largo} mm
              </span>
              {' · '}
              <span style={{ color: 'var(--fg)', fontWeight: 800 }}>
                {result.unidad} {result.unidadLabel}
              </span>
              <div style={{ fontSize: 10, opacity: 0.75, marginTop: 2 }}>
                {result.piezasPorPlancha} {result.piezasPorPlancha === 1 ? 'pieza' : 'piezas'} por plancha
              </div>
            </div>
          ) : (
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)',
              fontWeight: 600, marginTop: 4, letterSpacing: '0.04em',
            }}>
              Ingresá ancho y largo
            </div>
          )}
        </div>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 22, fontWeight: 800,
          color: 'var(--fg)', letterSpacing: '-0.02em', flexShrink: 0,
        }}>
          {window.fmtMoney(result.precioFinal)}
        </div>
      </button>

      {open && <div style={{
        padding: '4px 18px 16px',
        borderTop: '1px dashed var(--border)',
      }}>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 9, fontWeight: 700,
          color: 'var(--muted)', letterSpacing: '0.2em', textTransform: 'uppercase',
          padding: '10px 0 8px',
        }}>// Paso a paso</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map((r, i) => (
            <div key={i} style={{
              paddingBottom: 10,
              borderBottom: i < rows.length - 1 ? '1px solid var(--border)' : 'none',
            }}>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 9, fontWeight: 700,
                letterSpacing: '0.12em', textTransform: 'uppercase',
                color: r.highlight ? 'var(--accent)' : 'var(--muted)',
                marginBottom: 3,
              }}>{String(i + 1).padStart(2, '0')} · {r.label}</div>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)',
                fontWeight: 500, lineHeight: 1.5, wordBreak: 'break-word',
              }}>{r.expr}</div>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 16, fontWeight: 800,
                color: r.highlight ? 'var(--accent)' : 'var(--fg)',
                marginTop: 3, letterSpacing: '-0.01em',
              }}>= {r.value}</div>
            </div>
          ))}
        </div>
      </div>}
    </div>
  );
}

function CalculatorScreen({ state, setState, calibreStyle, sliderStyle, onGenerate, onShowBreakdown, onShowHistory, historyCount, onCycleTheme }) {
  const s = state;
  const materials = ['FRIO', 'CALIENTE', 'GALVANIZADA', 'PREPINTADA'];
  const sheet = window.SHEETS_DATA[s.material];

  const calibres = React.useMemo(() => {
    const seen = new Set();
    return sheet.filter(r => {
      const k = String(r.calibre);
      if (seen.has(k)) return false;
      seen.add(k); return true;
    }).map(r => String(r.calibre));
  }, [s.material]);

  const colors = React.useMemo(() => {
    if (s.material !== 'PREPINTADA') return [];
    return sheet.filter(r => String(r.calibre) === String(s.calibre)).map(r => r.color);
  }, [s.material, s.calibre]);

  React.useEffect(() => {
    if (!calibres.includes(s.calibre)) {
      setState(p => ({ ...p, calibre: calibres[0] }));
    }
  }, [s.material]);
  React.useEffect(() => {
    if (s.material === 'PREPINTADA' && colors.length && !colors.includes(s.color)) {
      setState(p => ({ ...p, color: colors[0] }));
    }
  }, [s.material, s.calibre, colors.join('|')]);

  const result = window.calculate(s);
  const isPrepintada = s.material === 'PREPINTADA';

  return (
    <div style={{
      background: 'var(--bg)', height: '100%',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        padding: '10px 10px 10px',
        borderBottom: '1.5px solid var(--border)',
        display: 'flex', alignItems: 'center',
        background: 'var(--bg)', flexShrink: 0, gap: 6,
      }}>
        <div style={{
          flexShrink: 0, minWidth: 0,
          maxWidth: 'min(24vw, 92px)',
        }}>
          <div
            role="img"
            aria-label="Giraudo"
            style={{
              height: 20, width: 'clamp(62px, 20vw, 90px)',
              backgroundColor: 'var(--terracotta)',
              WebkitMaskImage: 'url(logo-mask.png?v=11)',
              maskImage: 'url(logo-mask.png?v=11)',
              WebkitMaskRepeat: 'no-repeat', maskRepeat: 'no-repeat',
              WebkitMaskPosition: 'left center', maskPosition: 'left center',
              WebkitMaskSize: 'contain', maskSize: 'contain',
            }}
          />
          <div style={{
            fontFamily: 'var(--mono)', fontWeight: 700,
            color: 'var(--muted)', textTransform: 'uppercase',
            marginTop: 3, whiteSpace: 'nowrap',
            overflow: 'hidden', textOverflow: 'ellipsis',
            fontSize: 'clamp(6px, 1.6vw, 8px)',
            letterSpacing: 'clamp(0.04em, 0.5vw, 0.18em)',
          }}>Carpintería Metálica</div>
        </div>
        <div style={{
          flex: 1, textAlign: 'center', minWidth: 0,
          fontFamily: 'var(--sans)', fontWeight: 900,
          color: 'var(--fg)',
          fontSize: 'clamp(15px, 5.2vw, 28px)',
          letterSpacing: '-0.04em',
          overflow: 'hidden', whiteSpace: 'nowrap',
        }}>PLEGADOS</div>
        <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
          <button
            onClick={onCycleTheme}
            title="Cambiar tema"
            style={{
              width: 32, height: 32, border: '1.5px solid var(--border)',
              borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--muted)', background: 'transparent', cursor: 'pointer',
            }}
          >
            <Icon.Theme size={18}/>
          </button>
          <button
            onClick={onShowHistory}
            title="Presupuestos guardados"
            style={{
              width: 32, height: 32, border: '1.5px solid var(--border)',
              borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--fg)', background: 'transparent', cursor: 'pointer',
              position: 'relative',
            }}
          >
            <Icon.History size={18} />
            {historyCount > 0 && (
              <span style={{
                position: 'absolute', top: -5, right: -5,
                minWidth: 18, height: 18, padding: '0 5px',
                borderRadius: 9, background: 'var(--accent)', color: '#fff',
                fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 800,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{historyCount}</span>
            )}
          </button>
          <button
            onClick={() => {
              if (confirm('¿Limpiar todos los valores?')) {
                setState({
                  material: 'FRIO', calibre: '20', color: 'Blanca',
                  ancho: '', largo: '', cantidad: '1',
                  envio: 3, desperdicio: 5, manoObra: 2,
                  cliente: '', trabajo: '', plazo: '7',
                });
              }
            }}
            title="Limpiar valores"
            style={{
              width: 32, height: 32, border: '1.5px solid var(--border)',
              borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--muted)', background: 'transparent', cursor: 'pointer',
            }}
          >
            <Icon.Cog size={18} />
          </button>
        </div>
      </div>

      <div style={{ padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 20, flex: 1, overflow: 'auto', minHeight: 0 }}>

        <div>
          <FieldLabel icon={<Icon.Material size={13}/>}>Material</FieldLabel>
          <MaterialTabs value={s.material} onChange={m => setState(p => ({ ...p, material: m }))} options={materials}/>
        </div>

        <div>
          <FieldLabel icon={<Icon.Calibre size={13}/>} detail={sheet.find(r => String(r.calibre) === String(s.calibre))?.espesor_mm ? `${sheet.find(r => String(r.calibre) === String(s.calibre)).espesor_mm} mm` : ''}>
            Calibre
          </FieldLabel>
          <CalibreSelector value={s.calibre} onChange={c => setState(p => ({ ...p, calibre: c }))} options={calibres} style={calibreStyle}/>
        </div>

        {isPrepintada && (
          <div>
            <FieldLabel icon={<Icon.Palette size={13}/>}>Color</FieldLabel>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {colors.map(c => {
                const active = c === s.color;
                const swatch = {
                  'Blanca': '#f5f3ee', 'Negra': '#1a1a1a', 'Gris': '#808080',
                  'Verde': '#2f6b3a', 'Verde Ingles': '#2f4a34',
                  'Roja': '#b83020', 'Rojo Teja': '#b83020',
                  'Azul Milenium': '#1e3a6b', 'Azul': '#1e3a6b',
                }[c] || '#888';
                return (
                  <button key={c}
                    onClick={() => setState(p => ({ ...p, color: c }))}
                    style={{
                      flex: '1 1 calc(50% - 4px)', minWidth: 0, height: 52, borderRadius: 4,
                      border: active ? '2px solid var(--accent)' : '1.5px solid var(--border)',
                      background: active ? 'var(--accent-soft)' : 'var(--surface)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                      fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 700,
                      color: 'var(--fg)', cursor: 'pointer',
                      textTransform: 'uppercase', letterSpacing: '0.05em',
                    }}
                  >
                    <div style={{ width: 16, height: 16, background: swatch, border: '1px solid var(--border)', flexShrink: 0 }}/>
                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c}</span>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 12 }}>
          <div>
            <FieldLabel icon={<Icon.Ruler size={13}/>} detail={`máx ${result?.row?.ancho_max_mm || 0}`}>Ancho</FieldLabel>
            <NumInput value={s.ancho} onChange={v => setState(p => ({ ...p, ancho: v }))} suffix="MM" placeholder="0"/>
          </div>
          <div>
            <FieldLabel icon={<Icon.Ruler size={13}/>} detail={`máx ${result?.row?.largo_max_mm || 0}`}>Largo</FieldLabel>
            <NumInput value={s.largo} onChange={v => setState(p => ({ ...p, largo: v }))} suffix="MM" placeholder="0"/>
          </div>
        </div>

        <div>
          <FieldLabel icon={<Icon.Stack size={13}/>}>Cantidad de piezas</FieldLabel>
          <NumInput value={s.cantidad} onChange={v => setState(p => ({ ...p, cantidad: v }))} suffix="UNID." placeholder="1"/>
        </div>

        {result?.overMax && (
          <div style={{
            padding: '12px 14px', background: '#2a1810',
            border: '1.5px solid #8a4a10', borderRadius: 4,
            color: '#ffb366', display: 'flex', gap: 10, alignItems: 'flex-start',
            fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
          }}>
            <div style={{ marginTop: 1 }}><Icon.Warning size={18} color="#ffb366"/></div>
            <div>
              <div style={{ fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.05em', fontSize: 11, marginBottom: 2 }}>
                Supera medida comercial
              </div>
              Revisar desarrollo o dividir en piezas.
            </div>
          </div>
        )}

        <FormulaSection result={result} state={s}/>

        <div style={{
          display: 'flex', flexDirection: 'column', gap: 18,
          padding: '18px 0 6px',
          borderTop: '1.5px dashed var(--border)',
        }}>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
            color: 'var(--muted)', letterSpacing: '0.2em', textTransform: 'uppercase',
          }}>// Modificadores</div>

          <div>
            <FieldLabel icon={<Icon.Truck size={13}/>}>Envío</FieldLabel>
            <Slider value={s.envio} onChange={v => setState(p => ({ ...p, envio: v }))} min={0} max={10} step={0.5} suffix="%" style={sliderStyle}/>
          </div>
          <div>
            <FieldLabel icon={<Icon.Scissors size={13}/>}>Desperdicio</FieldLabel>
            <Slider value={s.desperdicio} onChange={v => setState(p => ({ ...p, desperdicio: v }))} min={0} max={10} step={0.5} suffix="%" style={sliderStyle}/>
          </div>
          <div>
            <FieldLabel icon={<Icon.Wrench size={13}/>}>Mano de Obra (multiplicador)</FieldLabel>
            <Slider value={s.manoObra} onChange={v => setState(p => ({ ...p, manoObra: v }))} min={1} max={4} step={0.25} suffix="×" style={sliderStyle}/>
          </div>
        </div>
      </div>

      <div style={{
        padding: '14px 16px calc(14px + env(safe-area-inset-bottom))',
        background: 'var(--fg)', color: 'var(--bg)',
        borderTop: '2px solid var(--accent)',
        flexShrink: 0,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, gap: 12 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 9, fontWeight: 700,
              letterSpacing: '0.18em', opacity: 0.55, textTransform: 'uppercase',
            }}>Precio Final</div>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 30, fontWeight: 800,
              letterSpacing: '-0.02em', marginTop: 2, color: 'var(--accent)',
            }}>
              {result ? window.fmtMoney(result.precioFinal) : '$ 0'}
            </div>
          </div>
          <button onClick={onShowBreakdown} style={{
            height: 44, padding: '0 14px', background: 'transparent',
            border: '1.5px solid rgba(255,255,255,0.3)',
            borderRadius: 4, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            color: 'var(--bg)',
            fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 800,
            letterSpacing: '0.1em', textTransform: 'uppercase', flexShrink: 0,
          }}>
            Ver detalle
            <Icon.ArrowRight size={14} color="currentColor"/>
          </button>
        </div>
        <button onClick={onGenerate} disabled={result?.overMax}
          style={{
            width: '100%', height: 52, background: 'var(--accent)',
            color: '#fff', border: 'none', borderRadius: 4,
            fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 800,
            letterSpacing: '0.1em', textTransform: 'uppercase',
            cursor: result?.overMax ? 'not-allowed' : 'pointer',
            opacity: result?.overMax ? 0.4 : 1,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          }}>
          Generar Presupuesto
          <Icon.ArrowRight size={18} color="#fff"/>
        </button>
      </div>
    </div>
  );
}

function BreakdownScreen({ state, onBack }) {
  const result = window.calculate(state);
  if (!result) return null;

  const rows = [
    { label: 'Abuelo', pct: 40, value: result.reparto.abuelo, code: 'AB' },
    { label: 'Víctor', pct: 30, value: result.reparto.victor, code: 'VI' },
    { label: 'Manu',   pct: 30, value: result.reparto.manu,   code: 'MA' },
  ];

  return (
    <div style={{ background: 'var(--bg)', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        padding: '18px 20px 14px',
        borderBottom: '1.5px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          width: 40, height: 40, border: '1.5px solid var(--border)',
          background: 'var(--surface)', borderRadius: 4, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--fg)',
        }}><Icon.ArrowLeft size={18}/></button>
        <div>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
            color: 'var(--muted)', letterSpacing: '0.18em',
          }}>// DESGLOSE · PRIVADO</div>
          <div style={{
            fontFamily: 'var(--sans)', fontSize: 22, fontWeight: 900,
            color: 'var(--fg)', letterSpacing: '-0.02em', marginTop: 2,
          }}>VER DETALLE</div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '20px', minHeight: 0 }}>
        <div style={{
          border: '1.5px solid var(--border)', borderRadius: 4,
          background: 'var(--surface)', marginBottom: 16,
        }}>
          {[
            ['Costo de material', result.costoBase],
            ['Envío + desperdicio', result.costoNeto - result.costoBase],
            ['Mano de obra (×' + state.manoObra + ')', result.precioFinal - result.costoNeto],
          ].map(([label, value], i) => (
            <div key={i} style={{
              padding: '14px 16px',
              borderBottom: '1px solid var(--border)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            }}>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 600, color: 'var(--muted)' }}>
                {label}
              </span>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 16, fontWeight: 700, color: 'var(--fg)' }}>
                {window.fmtMoney(value)}
              </span>
            </div>
          ))}
          <div style={{
            padding: '16px', display: 'flex', justifyContent: 'space-between',
            alignItems: 'baseline', background: 'var(--surface-2)',
          }}>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 800, color: 'var(--fg)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
              Precio Final
            </span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 22, fontWeight: 800, color: 'var(--fg)' }}>
              {window.fmtMoney(result.precioFinal)}
            </span>
          </div>
        </div>

        <div style={{
          padding: '14px 16px', background: 'var(--accent-soft)',
          border: '1.5px solid var(--accent)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          borderRadius: 4, marginBottom: 20,
        }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 800, color: 'var(--accent)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
            Ganancia Neta
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 22, fontWeight: 800, color: 'var(--accent)' }}>
            {window.fmtMoney(result.ganancia)}
          </span>
        </div>

        <div style={{
          fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
          color: 'var(--muted)', letterSpacing: '0.18em', textTransform: 'uppercase',
          marginBottom: 10,
        }}>// Reparto 40 / 30 / 30</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {rows.map(r => (
            <div key={r.code} style={{
              padding: '14px 16px', background: 'var(--surface)',
              border: '1.5px solid var(--border)', borderRadius: 4,
              display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <div style={{
                width: 44, height: 44, background: 'var(--fg)', color: 'var(--bg)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 800,
                letterSpacing: '0.05em',
              }}>{r.code}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--sans)', fontSize: 15, fontWeight: 800, color: 'var(--fg)' }}>{r.label}</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.05em' }}>
                  {r.pct}% de ganancia
                </div>
              </div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 18, fontWeight: 800, color: 'var(--fg)' }}>
                {window.fmtMoney(r.value)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ClientFormScreen({ state, setState, onBack, onExport, onSave }) {
  return (
    <div style={{ background: 'var(--bg)', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        padding: '18px 20px 14px',
        borderBottom: '1.5px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          width: 40, height: 40, border: '1.5px solid var(--border)',
          background: 'var(--surface)', borderRadius: 4, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--fg)',
        }}><Icon.ArrowLeft size={18}/></button>
        <div>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
            color: 'var(--muted)', letterSpacing: '0.18em',
          }}>PASO 2 DE 3</div>
          <div style={{
            fontFamily: 'var(--sans)', fontSize: 22, fontWeight: 900,
            color: 'var(--fg)', letterSpacing: '-0.02em', marginTop: 2,
          }}>DATOS DEL CLIENTE</div>
        </div>
      </div>

      <div style={{ padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 20, flex: 1, overflow: 'auto', minHeight: 0 }}>
        <div>
          <FieldLabel>Nombre del cliente</FieldLabel>
          <TextInput value={state.cliente} onChange={v => setState(p => ({ ...p, cliente: v }))} placeholder="Ej. Construcciones Pérez"/>
        </div>
        <div>
          <FieldLabel>Trabajo a realizar</FieldLabel>
          <TextInput multiline value={state.trabajo} onChange={v => setState(p => ({ ...p, trabajo: v }))}/>
        </div>
        <div>
          <FieldLabel detail="DÍAS">Plazo de entrega</FieldLabel>
          <NumInput value={state.plazo} onChange={v => setState(p => ({ ...p, plazo: v }))} suffix="DÍAS" placeholder="7"/>
        </div>

        <div style={{
          padding: '14px 16px', background: 'var(--surface)',
          border: '1.5px solid var(--border)', borderRadius: 4,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
        }}>
          <div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 700, color: 'var(--fg)' }}>
              Mostrar medidas exactas
            </div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>
              Incluir ancho y largo del desarrollo en el PDF.
            </div>
          </div>
          <Toggle value={state.mostrarMedidas} onChange={v => setState(p => ({ ...p, mostrarMedidas: v }))}/>
        </div>

        <div style={{
          padding: '14px 16px',
          background: 'var(--surface-2)',
          border: '1.5px dashed var(--border)',
          borderRadius: 4,
          fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--muted)',
          lineHeight: 1.8, fontWeight: 600,
        }}>
          <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 6, color: 'var(--fg)' }}>
            // Resumen del cálculo
          </div>
          <div>MATERIAL   {state.material}{state.material === 'PREPINTADA' ? ` · ${state.color}` : ''}</div>
          <div>CALIBRE    {state.calibre}</div>
          <div>MEDIDAS    {state.ancho || '—'} × {state.largo || '—'} mm</div>
          <div>CANTIDAD   {state.cantidad}</div>
          <div style={{ color: 'var(--accent)', fontWeight: 800, marginTop: 4 }}>
            TOTAL      {window.fmtMoney(window.calculate(state)?.precioFinal)}
          </div>
        </div>
      </div>

      <div style={{
        padding: '14px 16px calc(14px + env(safe-area-inset-bottom))', background: 'var(--bg)',
        borderTop: '1.5px solid var(--border)', flexShrink: 0,
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        <button onClick={onExport} style={{
          width: '100%', height: 52, background: 'var(--accent)',
          color: '#fff', border: 'none', borderRadius: 4,
          fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 800,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        }}>
          <Icon.Share size={18} color="#fff"/>
          Crear PDF y Compartir
        </button>
        <button onClick={onSave} style={{
          width: '100%', height: 44, background: 'transparent',
          color: 'var(--fg)', border: '1.5px solid var(--fg)', borderRadius: 4,
          fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 800,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Icon.Save size={16}/>
          Guardar Presupuesto
        </button>
      </div>
    </div>
  );
}

function PDFPreviewScreen({ state, onBack, onShare, flash }) {
  const result = window.calculate(state);
  const today = new Date().toLocaleDateString('es-AR', { day: '2-digit', month: '2-digit', year: 'numeric' });
  const pdfRef = React.useRef(null);
  const [busy, setBusy] = React.useState(null);

  const filename = window.safeFilename(state.cliente);
  const shareText = `Presupuesto Giraudo Carpintería Metálica\nCliente: ${state.cliente || '—'}\nTotal: ${window.fmtMoney(result?.precioFinal)}`;

  const handleDownload = async () => {
    setBusy('dl');
    try {
      await window.downloadPDF(state, result, filename);
      flash && flash('PDF descargado');
    } catch (err) {
      console.error(err);
      alert('Error generando el PDF: ' + (err.message || err));
    } finally { setBusy(null); }
  };

  const handleShare = async () => {
    setBusy('wa');
    try {
      const outcome = await window.sharePDF(state, result, filename, shareText);
      if (outcome === 'shared' || outcome === 'fallback') {
        flash && flash(outcome === 'shared' ? 'PDF compartido' : 'PDF descargado — abrí WhatsApp');
        setTimeout(() => onShare && onShare(), 1200);
      }
    } catch (err) {
      console.error(err);
      alert('Error al compartir: ' + (err.message || err));
    } finally { setBusy(null); }
  };

  return (
    <div style={{ background: '#1a1a1a', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        padding: '18px 20px 14px',
        background: 'var(--bg)',
        borderBottom: '1.5px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          width: 40, height: 40, border: '1.5px solid var(--border)',
          background: 'var(--surface)', borderRadius: 4, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--fg)',
        }}><Icon.ArrowLeft size={18}/></button>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
            color: 'var(--muted)', letterSpacing: '0.18em',
          }}>PASO 3 DE 3</div>
          <div style={{
            fontFamily: 'var(--sans)', fontSize: 22, fontWeight: 900,
            color: 'var(--fg)', letterSpacing: '-0.02em', marginTop: 2,
          }}>VISTA PREVIA</div>
        </div>
      </div>

      <div style={{ padding: 16, flex: 1, overflow: 'auto', minHeight: 0 }}>
        <div ref={pdfRef} style={{
          background: '#f5f3ee', color: '#1a1a1a',
          fontFamily: 'Georgia, serif',
          boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
          position: 'relative',
        }}>
          <div style={{
            padding: '14px 20px 14px', background: '#1a1a1a', color: '#f5f3ee',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            borderBottom: '3px solid #E85A1A', gap: 10,
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 7.5, fontWeight: 700,
                letterSpacing: '0.22em', opacity: 0.55, marginBottom: 4,
              }}>PLEGADOS</div>
              <img src="logo-terracotta.png" alt="Giraudo" style={{
                height: 26, width: 'auto', display: 'block',
              }}/>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 7, fontWeight: 700,
                letterSpacing: '0.15em', marginTop: 4, opacity: 0.7,
              }}>CARPINTERÍA METÁLICA</div>
            </div>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 7.5, lineHeight: 1.5,
              textAlign: 'right', opacity: 0.85, letterSpacing: '0.02em',
            }}>
              <div>AV SARMIENTO 453 · RÍO PRIMERO</div>
              <div>TEL 3574-408788 / 408785</div>
              <div>victorgiraudo@rioprim.com.ar</div>
              <div>@giraudo_carpinteriametalica</div>
            </div>
          </div>

          <div style={{
            padding: '14px 20px 10px', borderBottom: '1px solid #d4cfc2',
            display: 'flex', justifyContent: 'space-between',
            fontFamily: 'var(--mono)', fontSize: 9, fontWeight: 700,
            letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>
            <div>
              <div style={{ color: '#8a8576' }}>FECHA</div>
              <div style={{ fontSize: 11, color: '#1a1a1a', marginTop: 2 }}>{today}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ color: '#8a8576' }}>VALIDEZ</div>
              <div style={{ fontSize: 11, color: '#1a1a1a', marginTop: 2 }}>3 DÍAS</div>
            </div>
          </div>

          <div style={{ padding: '16px 20px 12px' }}>
            <Field label="CLIENTE">{state.cliente || '—'}</Field>
            <Field label="TRABAJO A REALIZAR">{state.trabajo}</Field>
          </div>

          <div style={{
            padding: '12px 20px',
            borderTop: '1px solid #d4cfc2',
            borderBottom: '1px solid #d4cfc2',
            background: '#ede9df',
          }}>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 8, fontWeight: 700,
              letterSpacing: '0.15em', color: '#8a8576', marginBottom: 6,
            }}>ESPECIFICACIONES</div>
            <div style={{ fontFamily: 'Georgia, serif', fontSize: 11, lineHeight: 1.7, color: '#1a1a1a' }}>
              – Tipo de chapa: <b>{state.material}{state.material === 'PREPINTADA' ? ` · ${state.color}` : ''}</b><br/>
              – Calibre: <b>{state.calibre}</b><br/>
              – Cantidad de piezas: <b>{state.cantidad}</b>
              {state.mostrarMedidas && (
                <><br/>– Desarrollo: <b>{state.ancho} mm × {state.largo} mm</b></>
              )}
            </div>
          </div>

          <div style={{ padding: '14px 20px', display: 'flex', gap: 20 }}>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 8, fontWeight: 700,
                letterSpacing: '0.15em', color: '#8a8576', marginBottom: 4,
              }}>INCLUYE</div>
              <div style={{ fontFamily: 'Georgia, serif', fontSize: 11, lineHeight: 1.6, color: '#1a1a1a' }}>
                – Corte<br/>– Plegado<br/>– Material
              </div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 8, fontWeight: 700,
                letterSpacing: '0.15em', color: '#8a8576', marginBottom: 4,
              }}>PLAZO DE ENTREGA</div>
              <div style={{ fontFamily: 'Georgia, serif', fontSize: 11, lineHeight: 1.6, color: '#1a1a1a' }}>
                {state.plazo} días desde<br/>la confirmación.
              </div>
            </div>
          </div>

          <div style={{
            padding: '16px 20px', background: '#1a1a1a', color: '#f5f3ee',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.2em',
            }}>TOTAL</div>
            <div style={{
              fontFamily: 'var(--sans)', fontSize: 22, fontWeight: 900,
              letterSpacing: '-0.02em', color: '#E85A1A',
            }}>{result ? window.fmtMoney(result.precioFinal) : '$ 0'}</div>
          </div>

          <div style={{ padding: '14px 20px' }}>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 8, fontWeight: 700,
              letterSpacing: '0.15em', color: '#8a8576', marginBottom: 4,
            }}>FORMAS DE PAGO</div>
            <div style={{ fontFamily: 'Georgia, serif', fontSize: 10.5, lineHeight: 1.5, color: '#1a1a1a' }}>
              60% al confirmar, resto contra entrega.
            </div>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 8, fontWeight: 700,
              letterSpacing: '0.15em', color: '#8a8576', marginTop: 10, marginBottom: 4,
            }}>OBSERVACIONES</div>
            <div style={{ fontFamily: 'Georgia, serif', fontSize: 10, lineHeight: 1.5, color: '#4a4637', fontStyle: 'italic' }}>
              El presente presupuesto podrá ajustarse en caso de modificar medidas o materiales al iniciar el trabajo.
            </div>
          </div>

          <div style={{ height: 14, background: '#E85A1A' }}/>
        </div>
      </div>

      <div style={{
        padding: '14px 16px calc(14px + env(safe-area-inset-bottom))', background: 'var(--bg)',
        borderTop: '1.5px solid var(--border)',
        display: 'flex', gap: 8, flexShrink: 0,
      }}>
        <button onClick={onBack} disabled={!!busy} style={{
          width: 52, height: 52, border: '1.5px solid var(--border)',
          background: 'var(--surface)', borderRadius: 4, cursor: busy ? 'wait' : 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--fg)', flexShrink: 0, opacity: busy ? 0.5 : 1,
        }}><Icon.ArrowLeft size={18}/></button>
        <button onClick={handleDownload} disabled={!!busy} style={{
          flex: 1, height: 52, background: 'var(--fg)',
          color: 'var(--bg)', border: 'none', borderRadius: 4,
          fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 800,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          cursor: busy ? 'wait' : 'pointer', opacity: busy && busy !== 'dl' ? 0.5 : 1,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Icon.Save size={16} color="currentColor"/>
          {busy === 'dl' ? 'Generando…' : 'Descargar'}
        </button>
        <button onClick={handleShare} disabled={!!busy} style={{
          flex: 1.3, height: 52, background: '#25D366',
          color: '#fff', border: 'none', borderRadius: 4,
          fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 800,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          cursor: busy ? 'wait' : 'pointer', opacity: busy && busy !== 'wa' ? 0.5 : 1,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Icon.WhatsApp size={16} color="#fff"/>
          {busy === 'wa' ? 'Compartiendo…' : 'WhatsApp'}
        </button>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 8, fontWeight: 700,
        letterSpacing: '0.15em', color: '#8a8576', marginBottom: 3,
      }}>{label}</div>
      <div style={{ fontFamily: 'Georgia, serif', fontSize: 13, lineHeight: 1.45, color: '#1a1a1a', fontWeight: 600 }}>
        {children}
      </div>
    </div>
  );
}

function Toast({ text, onClose }) {
  React.useEffect(() => {
    const t = setTimeout(onClose, 2400);
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{
      position: 'absolute', bottom: 110, left: 16, right: 16, zIndex: 40,
      padding: '12px 16px', background: 'var(--fg)', color: 'var(--bg)',
      borderLeft: '3px solid var(--accent)',
      display: 'flex', gap: 10, alignItems: 'center',
      fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 700,
    }}>
      <Icon.Check size={16} color="var(--accent)"/>
      {text}
    </div>
  );
}

function HistoryScreen({ onBack, onLoad }) {
  const [history, setHistory] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('giraudo_history') || '[]'); } catch { return []; }
  });

  const remove = (id) => {
    if (!confirm('¿Eliminar este presupuesto guardado?')) return;
    const next = history.filter(h => h.id !== id);
    setHistory(next);
    localStorage.setItem('giraudo_history', JSON.stringify(next));
  };

  const clearAll = () => {
    if (!confirm('¿Eliminar TODOS los presupuestos guardados?')) return;
    setHistory([]);
    localStorage.setItem('giraudo_history', '[]');
  };

  return (
    <div style={{ background: 'var(--bg)', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        padding: '18px 20px 14px', borderBottom: '1.5px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, border: '1.5px solid var(--border)', background: 'transparent',
          borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          color: 'var(--fg)',
        }}>
          <Icon.ArrowLeft size={16}/>
        </button>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700, color: 'var(--muted)', letterSpacing: '0.18em' }}>HISTORIAL</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 20, fontWeight: 900, color: 'var(--fg)', letterSpacing: '-0.02em' }}>
            Presupuestos Guardados
          </div>
        </div>
        {history.length > 0 && (
          <button onClick={clearAll} style={{
            fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700, color: 'var(--muted)',
            letterSpacing: '0.15em', textTransform: 'uppercase',
            background: 'transparent', border: 'none', cursor: 'pointer',
          }}>Borrar todo</button>
        )}
      </div>

      <div style={{ padding: '14px 16px 24px', display: 'flex', flexDirection: 'column', gap: 10, flex: 1, overflow: 'auto', minHeight: 0 }}>
        {history.length === 0 ? (
          <div style={{
            margin: 'auto', textAlign: 'center', padding: '40px 20px',
            fontFamily: 'var(--sans)', color: 'var(--muted)',
          }}>
            <div style={{ fontSize: 48, marginBottom: 8, opacity: 0.3 }}>⎙</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--fg)' }}>Sin presupuestos guardados</div>
            <div style={{ fontSize: 12, marginTop: 6, lineHeight: 1.4 }}>
              Calculá un presupuesto y tocá<br/>"Guardar Presupuesto" para verlo acá.
            </div>
          </div>
        ) : history.map(h => {
          const d = new Date(h.fecha);
          const fecha = d.toLocaleDateString('es-AR', { day: '2-digit', month: '2-digit', year: '2-digit' });
          const hora = d.toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit' });
          const s = h.state || {};
          return (
            <div key={h.id} style={{
              border: '1.5px solid var(--border)', borderRadius: 4, background: 'var(--surface)',
              overflow: 'hidden',
            }}>
              <button onClick={() => onLoad(h)} style={{
                display: 'block', width: '100%', padding: '12px 14px', textAlign: 'left',
                background: 'transparent', border: 'none', cursor: 'pointer',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                  <div style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 800, color: 'var(--fg)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {s.cliente || 'Sin cliente'}
                  </div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 14, fontWeight: 800, color: 'var(--accent)', flexShrink: 0 }}>
                    {window.fmtMoney(h.precioFinal)}
                  </div>
                </div>
                <div style={{
                  fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)',
                  letterSpacing: '0.1em', marginTop: 4,
                }}>
                  {s.material} · CAL {s.calibre} · {s.ancho || '—'}×{s.largo || '—'} · ×{s.cantidad}
                </div>
                <div style={{
                  fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)',
                  marginTop: 3, letterSpacing: '0.05em',
                }}>
                  {fecha} · {hora}
                </div>
              </button>
              <div style={{
                borderTop: '1px dashed var(--border)',
                display: 'flex',
              }}>
                <button onClick={() => onLoad(h)} style={{
                  flex: 1, padding: '10px', background: 'transparent', border: 'none',
                  fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 800, color: 'var(--fg)',
                  letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
                }}>Cargar</button>
                <button onClick={() => remove(h.id)} style={{
                  flex: 1, padding: '10px', background: 'transparent', border: 'none',
                  borderLeft: '1px dashed var(--border)',
                  fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 800, color: 'var(--muted)',
                  letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
                }}>Eliminar</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, {
  CalculatorScreen, BreakdownScreen, ClientFormScreen, PDFPreviewScreen, HistoryScreen, Toast, FormulaSection,
});
