// screens.jsx — Welcome, dynamic step renderer, summary, success

// ─────────────────────────────────────────────────────────────
// Welcome screen
// ─────────────────────────────────────────────────────────────
function WelcomeScreen({ onStart }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: '#fff' }}>

      {/* Hero oscuro con logo y glow */}
      <div style={{
        padding: '36px 24px 36px',
        paddingTop: 'calc(36px + env(safe-area-inset-top))',
        background: 'linear-gradient(160deg, #07071A 0%, #0E1535 60%, #130E2E 100%)',
        color: '#fff', flex: '0 0 auto', position: 'relative', overflow: 'hidden',
      }}>
        {/* Glow orbs */}
        <div style={{
          position: 'absolute', top: -80, right: -60,
          width: 320, height: 320, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(238,45,143,0.22) 0%, transparent 65%)',
          pointerEvents: 'none',
        }} />
        <div style={{
          position: 'absolute', bottom: -60, left: -60,
          width: 240, height: 240, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(114,48,240,0.18) 0%, transparent 65%)',
          pointerEvents: 'none',
        }} />

        {/* Logo */}
        <div style={{ position: 'relative' }}>
          <img
            src="/logo-a1-broker2.png"
            alt="A1 Broker"
            style={{ height: 64, display: 'block' }}
          />
        </div>

        <div style={{ marginTop: 28, position: 'relative' }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 7,
            padding: '5px 12px',
            background: 'rgba(238,45,143,0.15)',
            border: '1px solid rgba(238,45,143,0.35)',
            borderRadius: 99,
            fontSize: 11.5, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase',
            color: '#F472B6',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#EE2D8F', display: 'inline-block', flexShrink: 0 }} />
            Cotizador online
          </div>
          <h1 style={{
            fontSize: 32, fontWeight: 800, lineHeight: 1.1,
            marginTop: 14, letterSpacing: -0.8,
          }}>
            Cotizá tu seguro<br />
            <span style={{
              background: 'linear-gradient(90deg, #EE2D8F 0%, #7230F0 100%)',
              WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
            }}>en 5 minutos</span>.
          </h1>
          <p style={{
            marginTop: 14, fontSize: 15, lineHeight: 1.6,
            color: 'rgba(255,255,255,0.62)', maxWidth: 300,
          }}>
            Un asesor te enviará la mejor oferta de varias compañías.
          </p>
        </div>
      </div>

      {/* Feature cards */}
      <div style={{ flex: 1, padding: '22px 20px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            {
              icon: '⚡',
              title: 'Rápido',
              desc: 'Menos de 5 minutos.',
              bg: '#FDF4FF',
              iconBg: 'linear-gradient(135deg, #EE2D8F, #7230F0)',
            },
            {
              icon: '🎁',
              title: '5% DESCUENTO EXTRA',
              desc: 'Cargá tu póliza o documentación y sumás un 5% de descuento.',
              bg: '#FFF0F9',
              iconBg: 'linear-gradient(135deg, #EE2D8F, #DB2777)',
            },
          ].map((it) => (
            <div key={it.title} style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '14px 16px', borderRadius: 16,
              background: it.bg,
            }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12,
                background: it.iconBg,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 20, flexShrink: 0,
              }}>{it.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: '#111' }}>{it.title}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 2 }}>{it.desc}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{
          padding: '12px 16px', borderRadius: 14,
          background: 'rgba(114,48,240,0.05)',
          border: '1px solid rgba(114,48,240,0.15)',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{ fontSize: 18, lineHeight: 1 }}>💾</div>
          <div style={{ flex: 1, fontSize: 13, lineHeight: 1.5, color: 'var(--ink-700)' }}>
            <strong>Tus datos quedan guardados.</strong> Si cerrás la página y volvés, seguís donde estabas.
          </div>
        </div>
      </div>

      <div style={{
        padding: '16px 20px calc(16px + env(safe-area-inset-bottom))',
        background: '#fff', borderTop: '1px solid var(--ink-100)',
      }}>
        <PrimaryButton onClick={onStart} icon={
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 2 }}>
            <path d="M5 12h14M13 6l6 6-6 6" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        }>
          Empezar ahora
        </PrimaryButton>
        <div style={{
          textAlign: 'center', fontSize: 11.5, color: 'var(--ink-400)',
          marginTop: 10,
        }}>
          A1 Broker · Matrícula SSN · a1broker.com.ar
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Generic step renderer — dispatches by kind
// ─────────────────────────────────────────────────────────────
function StepRenderer({ step, data, setField, error, uploadFn }) {
  const val = data[step.id];
  const onChange = (v) => setField(step.id, v);

  switch (step.kind) {
    case 'text':
      return (
        <Input
          value={val} onChange={(v) => onChange(step.transform ? step.transform(v) : v)}
          placeholder={step.placeholder}
          inputMode={step.inputMode}
          maxLength={step.maxLength}
          prefix={step.prefix} suffix={step.suffix}
          error={error} hint={step.hint}
          autoFocus
        />
      );

    case 'textarea':
      return <Textarea value={val} onChange={onChange} placeholder={step.placeholder} error={error} />;

    case 'date':
      return <DateInput value={val} onChange={onChange} error={error} />;

    case 'options':
      return <OptionList value={val} onChange={onChange} options={step.options} />;

    case 'multi':
      return <CheckList value={val} onChange={onChange} options={step.options} />;

    case 'yesno':
      return <YesNo value={val} onChange={onChange} />;

    case 'file':
      return (
        <FileUpload value={val} onChange={onChange}
          accept={step.accept} icon={step.icon} label={step.label || 'Elegir archivo'}
          uploadFn={uploadFn} />
      );

    case 'files':
      return (
        <FileUpload value={val} onChange={onChange}
          accept={step.accept} icon={step.icon}
          label={step.label || 'Agregar archivos'} multiple
          uploadFn={uploadFn} />
      );

    case 'address':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Input label="Calle" value={(val || {}).calle}
            onChange={(v) => onChange({ ...(val || {}), calle: v })} autoFocus
            error={error && error.calle} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Input label="Número" value={(val || {}).numero} inputMode="numeric"
              onChange={(v) => onChange({ ...(val || {}), numero: v })}
              error={error && error.numero} />
            <Input label="Piso / Depto" value={(val || {}).piso}
              onChange={(v) => onChange({ ...(val || {}), piso: v })} />
          </div>
        </div>
      );

    case 'locality':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Input label="Localidad" value={(val || {}).localidad}
            onChange={(v) => onChange({ ...(val || {}), localidad: v })} autoFocus
            error={error && error.localidad} />
          <Input label="Código postal" value={(val || {}).cp} inputMode="numeric" maxLength={8}
            onChange={(v) => onChange({ ...(val || {}), cp: v })}
            error={error && error.cp} />
        </div>
      );

    case 'contact':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Input label="Email" value={(val || {}).email} type="email" inputMode="email"
            placeholder="tu@email.com"
            onChange={(v) => onChange({ ...(val || {}), email: v })} autoFocus
            error={error && error.email} />
          <Input label="Teléfono / WhatsApp" value={(val || {}).tel} inputMode="tel"
            prefix="+54" placeholder="11 1234 5678"
            onChange={(v) => onChange({ ...(val || {}), tel: v })}
            error={error && error.tel} />
        </div>
      );

    case 'discount-upload':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{
            padding: 16, borderRadius: 16,
            background: 'linear-gradient(135deg, #0A2540 0%, #1E63B8 100%)',
            color: '#fff',
            display: 'flex', gap: 14, alignItems: 'center',
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', top: -20, right: -20,
              width: 100, height: 100, borderRadius: '50%',
              background: 'rgba(127,209,162,0.2)',
            }} />
            <div style={{
              width: 56, height: 56, borderRadius: 14,
              background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(10px)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 28, flexShrink: 0, position: 'relative',
            }}>🎁</div>
            <div style={{ position: 'relative' }}>
              <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>5% DESCUENTO EXTRA</div>
              <div style={{ fontSize: 13, opacity: 0.85, lineHeight: 1.4 }}>
                Si cargás tu póliza actual o documentación (DNI, F931, Recibo), sumás un 5% de <strong>DESCUENTO EXTRA</strong> en tu gestión.
              </div>
            </div>
          </div>
          <FileUpload value={val} onChange={onChange}
            accept=".pdf,image/*" icon="📎" multiple
            label="Subir póliza actual, DNI, F931 o recibo"
            uploadFn={uploadFn} />
          <div style={{ fontSize: 12, color: 'var(--ink-500)', textAlign: 'center' }}>
            Podés saltear este paso — no bloquea la cotización.
          </div>
        </div>
      );

    case 'auto-details':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Input label="N° de chasis" value={(val || {}).chasis}
            onChange={(v) => onChange({ ...(val || {}), chasis: v.toUpperCase() })} autoFocus />
          <Input label="N° de motor" value={(val || {}).motor}
            onChange={(v) => onChange({ ...(val || {}), motor: v.toUpperCase() })} />
          <Input label="Kilometraje actual" value={(val || {}).km} inputMode="numeric" suffix="km"
            onChange={(v) => onChange({ ...(val || {}), km: v })} />
          <Input label="Color" value={(val || {}).color}
            onChange={(v) => onChange({ ...(val || {}), color: v })} />
          <Input label="Marca y medida de cubiertas" value={(val || {}).cubiertas}
            placeholder="Ej: Pirelli 185/65 R15"
            onChange={(v) => onChange({ ...(val || {}), cubiertas: v })} />
        </div>
      );

    case 'auto-equip':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)', marginBottom: 8 }}>¿Tiene alarma?</div>
            <YesNo value={(val || {}).alarma} onChange={(v) => onChange({ ...(val || {}), alarma: v })} />
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)', marginBottom: 8 }}>Tipo de llave</div>
            <OptionList
              value={(val || {}).llave}
              onChange={(v) => onChange({ ...(val || {}), llave: v })}
              options={[
                { value: 'integrada', label: 'Integrada', desc: 'Llave con control remoto incluido' },
                { value: 'separada', label: 'Separada', desc: 'Llave y control por separado' },
              ]}
            />
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)', marginBottom: 8 }}>¿Tiene GNC?</div>
            <YesNo value={(val || {}).gnc} onChange={(v) => onChange({ ...(val || {}), gnc: v })} />
          </div>
        </div>
      );

    case 'home-m2':
      return (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Input label="Cubiertos" value={(val || {}).cubiertos} inputMode="numeric" suffix="m²"
            onChange={(v) => onChange({ ...(val || {}), cubiertos: v })} autoFocus
            error={error && error.cubiertos} />
          <Input label="Descubiertos" value={(val || {}).descubiertos} inputMode="numeric" suffix="m²"
            onChange={(v) => onChange({ ...(val || {}), descubiertos: v })} />
        </div>
      );

    case 'ap-norep':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Input label="CUIT de quien la solicita" value={(val || {}).cuit}
            inputMode="numeric" maxLength={13}
            onChange={(v) => onChange({ ...(val || {}), cuit: v })} autoFocus
            error={error && error.cuit} />
          <Input label="Suma asegurada" value={(val || {}).suma}
            prefix="$" inputMode="numeric"
            onChange={(v) => onChange({ ...(val || {}), suma: v })}
            error={error && error.suma} />
        </div>
      );

    case 'travel-dates':
      return (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <DateInput label="Salida" value={(val || {}).salida}
            onChange={(v) => onChange({ ...(val || {}), salida: v })} />
          <DateInput label="Regreso" value={(val || {}).regreso}
            onChange={(v) => onChange({ ...(val || {}), regreso: v })} />
        </div>
      );

    case 'travel-pre':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <YesNo value={(val || {}).tiene}
            onChange={(v) => onChange({ ...(val || {}), tiene: v })} />
          {(val || {}).tiene === 'si' && (
            <Textarea label="Contanos cuál"
              value={(val || {}).detalle}
              onChange={(v) => onChange({ ...(val || {}), detalle: v })}
              placeholder="Ej: embarazo de 16 semanas, hipertensión, etc." />
          )}
        </div>
      );

    default:
      return <div>Step kind no reconocido: {step.kind}</div>;
  }
}

// ─────────────────────────────────────────────────────────────
// Summary screen
// ─────────────────────────────────────────────────────────────
function SummarySection({ title, rows }) {
  const visibleRows = rows.filter(([, v]) => v !== undefined && v !== null && v !== '' && !(Array.isArray(v) && v.length === 0));
  if (!visibleRows.length) return null;
  return (
    <div style={{
      background: '#fff', border: '1px solid var(--ink-200)',
      borderRadius: 16, overflow: 'hidden', marginBottom: 12,
    }}>
      <div style={{
        padding: '10px 14px', background: 'var(--ink-50)',
        fontSize: 11.5, fontWeight: 700, letterSpacing: 0.6,
        textTransform: 'uppercase', color: 'var(--ink-500)',
        borderBottom: '1px solid var(--ink-100)',
      }}>{title}</div>
      <div>
        {visibleRows.map(([k, v], i) => (
          <div key={k} style={{
            padding: '12px 14px',
            borderBottom: i < visibleRows.length - 1 ? '1px solid var(--ink-100)' : 'none',
            display: 'flex', gap: 12, alignItems: 'flex-start',
          }}>
            <div style={{
              fontSize: 12.5, color: 'var(--ink-500)', flex: '0 0 40%',
              fontWeight: 500,
            }}>{k}</div>
            <div style={{
              fontSize: 13.5, color: 'var(--ink-900)', flex: 1,
              fontWeight: 500, wordBreak: 'break-word',
            }}>{v}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Success
// ─────────────────────────────────────────────────────────────
function SuccessScreen({ data, riskLabel, cotizacionId, onRestart, onCorrect, onOpenWhatsapp }) {
  const linkCotizacion = cotizacionId
    ? `${window.location.origin}/c/${cotizacionId}`
    : null;

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: '#fff', overflow: 'auto' }}>
      {/* Hero oscuro con glow */}
      <div style={{
        padding: '48px 24px 36px',
        paddingTop: 'calc(48px + env(safe-area-inset-top))',
        background: 'linear-gradient(160deg, #07071A 0%, #0E1535 60%, #130E2E 100%)',
        color: '#fff', textAlign: 'center', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -80, right: -60,
          width: 280, height: 280, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(238,45,143,0.2) 0%, transparent 65%)',
          pointerEvents: 'none',
        }} />
        <div style={{
          position: 'absolute', bottom: -60, left: -40,
          width: 200, height: 200, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(114,48,240,0.18) 0%, transparent 65%)',
          pointerEvents: 'none',
        }} />

        <div style={{
          width: 72, height: 72, borderRadius: '50%',
          background: 'linear-gradient(135deg, rgba(238,45,143,0.25), rgba(114,48,240,0.25))',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 18px',
          border: '2px solid rgba(238,45,143,0.5)',
          position: 'relative',
        }}>
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none">
            <path d="M4 12l5 5L20 6" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <h1 style={{ fontSize: 26, fontWeight: 800, letterSpacing: -0.5, position: 'relative' }}>
          ¡Datos recibidos! 🚀
        </h1>
        <p style={{
          marginTop: 10, fontSize: 14.5, lineHeight: 1.55, position: 'relative',
          color: 'rgba(255,255,255,0.7)', maxWidth: 300, margin: '10px auto 0',
        }}>
          Un asesor te responde con la mejor cotización de <strong style={{ color: '#fff' }}>{riskLabel}</strong> en breve.
        </p>
      </div>

      <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>

        {/* Link de la cotización */}
        {linkCotizacion && (
          <a href={linkCotizacion} target="_blank" rel="noopener"
            style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '12px 16px', borderRadius: 12,
              background: 'rgba(114,48,240,0.06)', border: '1.5px solid rgba(114,48,240,0.2)',
              color: '#7230F0', textDecoration: 'none', fontSize: 13,
            }}>
            <span style={{ fontSize: 18 }}>🔗</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600 }}>Ver cotización completa</div>
              <div style={{ fontSize: 11.5, opacity: .6, marginTop: 1, wordBreak: 'break-all' }}>{linkCotizacion}</div>
            </div>
          </a>
        )}

        {/* WhatsApp */}
        <PrimaryButton onClick={onOpenWhatsapp} icon={
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" style={{ marginLeft: 4 }}>
            <path d="M12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 1.75.46 3.45 1.32 4.95L2.05 22l5.25-1.38c1.45.79 3.08 1.21 4.74 1.21 5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.9-7.01A9.82 9.82 0 0 0 12.04 2z"/>
          </svg>
        }>
          Mandar link por WhatsApp
        </PrimaryButton>

        {/* Corregir / Nueva */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <GhostButton onClick={onCorrect}>✏️ Corregir datos</GhostButton>
          <GhostButton onClick={onRestart}>+ Nueva cotización</GhostButton>
        </div>

        <div style={{
          padding: 14,
          background: 'linear-gradient(135deg, rgba(238,45,143,0.05), rgba(114,48,240,0.05))',
          border: '1px solid rgba(114,48,240,0.12)',
          borderRadius: 14, fontSize: 13, color: 'var(--ink-500)', lineHeight: 1.5,
          textAlign: 'center',
        }}>
          ⏱️ Tiempo promedio de respuesta: <strong style={{ color: 'var(--ink-900)' }}>30 minutos</strong> en días hábiles.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WelcomeScreen, StepRenderer, SummarySection, SuccessScreen });
