// CronoDato — Perfil screen

const PerfilScreen = ({ onNav }) => {
  const [tab, setTab] = React.useState('datos');
  const [nombre, setNombre] = React.useState('Distribuidora Norte S.A.');
  const [emailContacto, setEmailContacto] = React.useState('admin@dnorte.com');
  const [emailFacturas, setEmailFacturas] = React.useState('compras@dnorte.com');
  const [passActual, setPassActual] = React.useState('');
  const [passNueva, setPassNueva] = React.useState('');
  const [passConfirm, setPassConfirm] = React.useState('');
  const [saved, setSaved] = React.useState(false);
  const [passError, setPassError] = React.useState('');
  const [passSaved, setPassSaved] = React.useState(false);

  const tabs = [
    { id: 'datos',       label: 'Mis datos',   icon: 'user' },
    { id: 'planes',      label: 'Planes',       icon: 'zap' },
    { id: 'facturacion', label: 'Facturación',  icon: 'receipt' },
  ];

  const pagos = [
    { fecha: '01/05/2025', concepto: 'Pack Estándar — 200 facturas', monto: '$16.000', estado: 'pagado', nro: 'CD-2025-0042' },
    { fecha: '02/04/2025', concepto: 'Pack Inicial — 50 facturas',   monto: '$5.000',  estado: 'pagado', nro: 'CD-2025-0031' },
    { fecha: '01/03/2025', concepto: 'Pack Inicial — 50 facturas',   monto: '$5.000',  estado: 'pagado', nro: 'CD-2025-0018' },
    { fecha: '28/02/2025', concepto: 'Pack Estándar — 200 facturas', monto: '$16.000', estado: 'cancelado', nro: 'CD-2025-0014' },
  ];

  const guardarDatos = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const cambiarPass = () => {
    setPassError('');
    if (!passActual) { setPassError('Ingresá tu contraseña actual'); return; }
    if (passNueva.length < 6) { setPassError('La nueva contraseña debe tener al menos 6 caracteres'); return; }
    if (passNueva !== passConfirm) { setPassError('Las contraseñas no coinciden'); return; }
    setPassSaved(true);
    setPassActual(''); setPassNueva(''); setPassConfirm('');
    setTimeout(() => setPassSaved(false), 3000);
  };

  const Field = ({ label, value, onChange, type = 'text', hint }) => (
    <div style={{ marginBottom: 16 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#64748B', marginBottom: 6 }}>{label}</label>
      <input type={type} value={value} onChange={e => onChange(e.target.value)}
        style={{ width: '100%', maxWidth: 400, fontFamily: "'DM Sans',sans-serif", fontSize: 14, padding: '9px 12px', border: '1.5px solid #E2E8F0', borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none' }}
        onFocus={e => { e.target.style.borderColor = '#059669'; e.target.style.boxShadow = '0 0 0 3px rgba(5,150,105,0.12)'; }}
        onBlur={e => { e.target.style.borderColor = '#E2E8F0'; e.target.style.boxShadow = 'none'; }}
      />
      {hint && <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 4 }}>{hint}</div>}
    </div>
  );

  const Card = ({ title, desc, children }) => (
    <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, marginBottom: 20, overflow: 'hidden' }}>
      <div style={{ padding: '16px 24px', borderBottom: '1px solid #F1F5F9' }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A' }}>{title}</div>
        {desc && <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>{desc}</div>}
      </div>
      <div style={{ padding: '20px 24px' }}>{children}</div>
    </div>
  );

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <Topbar title="Mi perfil" />
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {/* Tabs lateral */}
        <div style={{ width: 200, background: 'white', borderRight: '1px solid #E2E8F0', padding: '16px 12px', flexShrink: 0 }}>
          {/* Avatar */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '16px 0 20px', borderBottom: '1px solid #F1F5F9', marginBottom: 12 }}>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: '#047857', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, color: 'white', fontWeight: 700, marginBottom: 8 }}>
              {nombre.slice(0,2).toUpperCase()}
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A', textAlign: 'center', lineHeight: 1.3 }}>{nombre}</div>
            <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2 }}>Pack Estándar</div>
          </div>
          {tabs.map(t => (
            <div key={t.id} onClick={() => setTab(t.id)} style={{
              display: 'flex', alignItems: 'center', gap: 9,
              padding: '9px 12px', borderRadius: 6, cursor: 'pointer', marginBottom: 2,
              background: tab === t.id ? '#ECFDF5' : 'transparent',
              color: tab === t.id ? '#047857' : '#475569',
              fontWeight: tab === t.id ? 600 : 400, fontSize: 14,
              transition: 'background 120ms',
            }}
            onMouseEnter={e => { if (tab !== t.id) e.currentTarget.style.background = '#F8FAFC'; }}
            onMouseLeave={e => { if (tab !== t.id) e.currentTarget.style.background = 'transparent'; }}>
              <i data-lucide={t.icon} style={{ width: 16, height: 16, flexShrink: 0 }}></i>
              {t.label}
            </div>
          ))}
        </div>

        {/* Contenido */}
        <div style={{ flex: 1, overflowY: 'auto', padding: 28 }}>

          {/* ── MIS DATOS ── */}
          {tab === 'datos' && (
            <>
              <Card title="Datos de la empresa">
                <Field label="Nombre o razón social" value={nombre} onChange={setNombre} />
                <Field label="Email de contacto" type="email" value={emailContacto} onChange={setEmailContacto} hint="Donde recibís notificaciones de CronoDato" />
                <Field label="Email que envía facturas" type="email" value={emailFacturas} onChange={setEmailFacturas} hint="Desde donde nos mandás los PDF" />
                <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 4 }}>
                  <Btn onClick={guardarDatos}>Guardar cambios</Btn>
                  {saved && <span style={{ fontSize: 13, color: '#059669', display: 'flex', alignItems: 'center', gap: 5 }}>
                    <i data-lucide="check" style={{ width: 14, height: 14 }}></i> Guardado
                  </span>}
                </div>
              </Card>

              <Card title="Cambiar contraseña">
                {passError && <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 13, color: '#B91C1C', marginBottom: 14 }}>{passError}</div>}
                {passSaved && <div style={{ background: '#ECFDF5', border: '1px solid #A7F3D0', borderRadius: 6, padding: '8px 12px', fontSize: 13, color: '#047857', marginBottom: 14 }}>Contraseña actualizada correctamente</div>}
                <Field label="Contraseña actual" type="password" value={passActual} onChange={setPassActual} />
                <Field label="Nueva contraseña" type="password" value={passNueva} onChange={setPassNueva} hint="Mínimo 6 caracteres" />
                <Field label="Repetir nueva contraseña" type="password" value={passConfirm} onChange={setPassConfirm} />
                <Btn onClick={cambiarPass}>Cambiar contraseña</Btn>
              </Card>
            </>
          )}

          {/* ── PLANES ── */}
          {tab === 'planes' && (
            <>
              <Card title="Plan actual" desc="Tu pack prepago vigente">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
                  <div>
                    <div style={{ fontSize: 20, fontWeight: 700, color: '#0F172A', marginBottom: 4 }}>Pack Estándar</div>
                    <div style={{ fontSize: 13, color: '#64748B' }}>200 facturas incluidas · $16.000 ARS</div>
                    <div style={{ marginTop: 12, marginBottom: 6, display: 'flex', justifyContent: 'space-between', fontSize: 13, color: '#64748B' }}>
                      <span>Facturas usadas</span>
                      <span style={{ fontFamily: "'DM Mono',monospace", color: '#0F172A' }}>48 / 200</span>
                    </div>
                    <div style={{ height: 6, background: '#F1F5F9', borderRadius: 9999, overflow: 'hidden', width: 280 }}>
                      <div style={{ width: '24%', height: '100%', background: '#059669', borderRadius: 9999 }} />
                    </div>
                    <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 4 }}>152 facturas restantes</div>
                  </div>
                </div>
              </Card>

              <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A', marginBottom: 16 }}>Recargar o cambiar plan</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 24 }}>
                {[
                  { nombre: 'Pack Inicial', facturas: 50, precio: 5000, costo: 100 },
                  { nombre: 'Pack Estándar', facturas: 200, precio: 16000, costo: 80, actual: true },
                  { nombre: 'Pack Profesional', facturas: 100, precio: 9000, costo: 90, promo: true },
                ].map(plan => (
                  <div key={plan.nombre} style={{
                    border: `2px solid ${plan.actual ? '#059669' : '#E2E8F0'}`,
                    borderRadius: 10, padding: '18px 16px', position: 'relative',
                    background: plan.actual ? '#F0FDF4' : 'white',
                  }}>
                    {plan.actual && <div style={{ position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)', background: '#059669', color: 'white', fontSize: 10, fontWeight: 700, padding: '2px 10px', borderRadius: 9999, whiteSpace: 'nowrap' }}>PLAN ACTUAL</div>}
                    {plan.promo && <div style={{ position: 'absolute', top: -10, right: 12, background: '#059669', color: 'white', fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 9999 }}>PROMO</div>}
                    <div style={{ fontSize: 14, fontWeight: 700, color: '#0F172A', marginBottom: 8 }}>{plan.nombre}</div>
                    <div style={{ fontSize: 22, fontWeight: 800, color: plan.actual ? '#059669' : '#0F172A', fontFamily: "'DM Mono',monospace" }}>${plan.precio.toLocaleString('es-AR')}</div>
                    <div style={{ fontSize: 12, color: '#64748B', marginTop: 4 }}>{plan.facturas} facturas</div>
                    <div style={{ fontSize: 11, color: '#94A3B8', fontFamily: "'DM Mono',monospace" }}>${plan.costo} / factura</div>
                    {!plan.actual && (
                      <button style={{ marginTop: 14, width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 13, fontWeight: 600, padding: '8px', background: '#059669', color: 'white', border: 'none', borderRadius: 6, cursor: 'pointer' }}>
                        Contratar
                      </button>
                    )}
                  </div>
                ))}
              </div>
              <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8, padding: '14px 18px', fontSize: 13, color: '#64748B' }}>
                El pago se procesa a través de <strong>Mercado Pago</strong>. Las facturas se acreditan inmediatamente al confirmar el pago.
              </div>
            </>
          )}

          {/* ── FACTURACIÓN ── */}
          {tab === 'facturacion' && (
            <Card title="Historial de pagos" desc="Tus compras de packs prepago">
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: '#F8FAFC' }}>
                      {['Fecha', 'Concepto', 'Monto', 'Estado', 'Comprobante'].map(h => (
                        <th key={h} style={{ padding: '9px 14px', textAlign: 'left', fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#94A3B8', borderBottom: '1px solid #E2E8F0' }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {pagos.map((p, i) => (
                      <tr key={p.nro} style={{ borderBottom: i < pagos.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
                        <td style={{ padding: '12px 14px', color: '#64748B', fontFamily: "'DM Mono',monospace", fontSize: 12 }}>{p.fecha}</td>
                        <td style={{ padding: '12px 14px', color: '#0F172A' }}>{p.concepto}</td>
                        <td style={{ padding: '12px 14px', fontFamily: "'DM Mono',monospace", fontWeight: 600, color: '#047857' }}>{p.monto}</td>
                        <td style={{ padding: '12px 14px' }}>
                          <span style={{
                            fontSize: 11, fontWeight: 500, padding: '2px 8px', borderRadius: 9999,
                            background: p.estado === 'pagado' ? '#ECFDF5' : '#FEF2F2',
                            color: p.estado === 'pagado' ? '#047857' : '#B91C1C',
                          }}>
                            {p.estado === 'pagado' ? 'Pagado' : 'Cancelado'}
                          </span>
                        </td>
                        <td style={{ padding: '12px 14px' }}>
                          {p.estado === 'pagado' && (
                            <button style={{
                              fontFamily: "'DM Sans',sans-serif", fontSize: 12, fontWeight: 500, padding: '4px 10px',
                              background: 'white', color: '#475569', border: '1px solid #E2E8F0', borderRadius: 5, cursor: 'pointer',
                              display: 'inline-flex', alignItems: 'center', gap: 5,
                            }}>
                              <i data-lucide="download" style={{ width: 12, height: 12 }}></i> PDF
                            </button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Card>
          )}

        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PerfilScreen });
