/* screen-services.jsx — Panel de servicios y pagos + Checkout */
const { useState: useSvcState } = React;

const mxn = (n) => '$' + n.toLocaleString('es-MX');

const STAGE_TONE = {
  analisis: ['var(--c-blue-bg)', 'var(--c-blue)'],
  inscripcion: ['#FFF6E0', 'var(--yb-yellow-deep)'],
  gestion: ['#F5F3FF', '#7C3AED'],
};
const STAGE_INCL = {
  analisis: ['Requisitos de tu zona y alcaldía', 'Compliance Score inicial', 'Checklist de lo que falta', 'Lectura de documentos (OCR + IA)'],
  inscripcion: ['Todo el análisis incluido', 'Expediente con sello NOM-151', 'Firma electrónica JAAK', 'Alta ante la autoridad', 'Evidencia para auditoría'],
  gestion: ['Gestión presencial ante la autoridad', 'Representación y seguimiento', 'Resolución de observaciones', 'Reporte de estatus en tiempo real'],
};

/* ===== Services overview ===== */
function Services({ store }) {
  const { properties, nav } = store;
  return (
    <div className="pf-page">
      <div className="pf-page-head">
        <div style={{ flex: 1 }}>
          <h1>Servicios y pagos</h1>
          <p className="pf-muted" style={{ fontSize: 14.5, marginTop: 4 }}>Contrata cada etapa por inmueble. Precio plano, sin sorpresas.</p>
        </div>
      </div>

      {/* three stages */}
      <div className="pf-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)', marginBottom: 30 }}>
        {Object.values(PF_SERVICES).map(s => (
          <div key={s.key} className="pf-card" style={{ padding: 22, display: 'flex', flexDirection: 'column', border: s.key === 'inscripcion' ? '2px solid var(--yb-yellow)' : '1px solid var(--line)' }}>
            <span className="badge" style={{ background: STAGE_TONE[s.key][0], color: STAGE_TONE[s.key][1], alignSelf: 'flex-start' }}>Etapa {s.stage}</span>
            <h3 style={{ fontSize: 18, marginTop: 12 }}>{s.name}</h3>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, margin: '12px 0' }}>
              <span className="pf-num" style={{ fontFamily: 'var(--font-display)', fontSize: s.range ? 26 : 38, fontWeight: 800 }}>{s.range ? `${mxn(s.range[0])}–${s.range[1].toLocaleString('es-MX')}` : mxn(s.price)}</span>
              <span className="pf-muted" style={{ fontSize: 13 }}>MXN · {s.unit}</span>
            </div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 9, flex: 1 }}>
              {STAGE_INCL[s.key].map(t => <li key={t} style={{ display: 'flex', gap: 9, fontSize: 13.5 }}><Icon name="check" size={16} style={{ color: 'var(--c-emerald)', flex: '0 0 auto', marginTop: 1 }} /> {t}</li>)}
            </ul>
          </div>
        ))}
      </div>

      {/* per property progress */}
      <h2 style={{ fontSize: 18, marginBottom: 14 }}>Tus inmuebles y etapas</h2>
      <div className="pf-card" style={{ overflow: 'hidden' }}>
        {properties.map((p, i) => (
          <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 20px', borderBottom: i < properties.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <span style={{ width: 40, height: 40, borderRadius: 11, background: p.thumb, flex: '0 0 auto' }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
              <div className="pf-muted" style={{ fontSize: 12.5 }}>{p.alcaldia}</div>
            </div>
            <div style={{ display: 'flex', gap: 7 }}>
              {Object.values(PF_SERVICES).map(s => (
                <span key={s.key} className="badge" style={{ background: p.owned[s.key] ? 'var(--c-emerald-bg)' : 'var(--surface-2)', color: p.owned[s.key] ? 'var(--c-emerald-d)' : 'var(--faint)' }}>
                  {p.owned[s.key] ? <Icon name="check" size={12} /> : <span className="dot" style={{ background: 'var(--faint)' }} />} E{s.stage}
                </span>
              ))}
            </div>
            {(() => {
              const next = !p.owned.inscripcion ? 'inscripcion' : !p.owned.gestion ? 'gestion' : null;
              return next
                ? <button className="pf-btn pf-btn-yellow pf-btn-sm" onClick={() => { store.setCheckout({ propId: p.id, service: next }); nav('checkout'); }}>Contratar etapa {PF_SERVICES[next].stage}</button>
                : <span style={{ fontSize: 13, color: 'var(--c-emerald-d)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="shieldcheck" size={15} /> Completo</span>;
            })()}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ===== Checkout ===== */
function Checkout({ store }) {
  const co = store.checkout;
  const [done, setDone] = useSvcState(false);
  const [paying, setPaying] = useSvcState(false);
  const [method, setMethod] = useSvcState('card');
  if (!co) { store.nav('services'); return null; }
  const p = store.properties.find(x => x.id === co.propId);
  const s = PF_SERVICES[co.service];
  const price = s.range ? s.range[0] : s.price;
  const iva = Math.round(price * 0.16);
  const total = price + iva;

  const pay = () => {
    setPaying(true);
    setTimeout(() => {
      setPaying(false); setDone(true);
      const newOwned = { ...p.owned, [co.service]: true };
      const bump = co.service === 'inscripcion' ? 30 : 14;
      const newReqs = { ...p.reqs };
      if (co.service === 'inscripcion') { newReqs.padron = 'ok'; newReqs.hosp = 'ok'; newReqs.condo = 'ok'; }
      store.updateProperty(p.id, {
        owned: newOwned,
        score: Math.min(98, p.score + bump),
        stage: co.service === 'inscripcion' ? 'done' : p.stage,
        status: co.service === 'inscripcion' ? 'compliant' : p.status,
        reqs: newReqs,
      });
    }, 1900);
  };

  if (done) {
    return (
      <div className="pf-page" style={{ maxWidth: 560 }}>
        <div className="pf-card" style={{ padding: 44, textAlign: 'center' }}>
          <div style={{ width: 72, height: 72, borderRadius: 20, background: 'var(--c-emerald-bg)', color: 'var(--c-emerald-d)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px' }}><Icon name="check" size={36} /></div>
          <h1 style={{ fontSize: 25 }}>¡Pago confirmado!</h1>
          <p className="pf-muted" style={{ fontSize: 15, marginTop: 10, lineHeight: 1.55 }}>
            Contrataste <strong style={{ color: 'var(--ink)' }}>{s.name}</strong> para <strong style={{ color: 'var(--ink)' }}>{p.name}</strong>. {co.service === 'inscripcion' ? 'Comenzamos a armar tu expediente y a tramitar tu alta.' : 'Un especialista te contactará para iniciar la gestión.'}
          </p>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 26 }}>
            <button className="pf-btn pf-btn-yellow pf-btn-lg" onClick={() => store.nav('property', p.id)}>Ver expediente</button>
            <button className="pf-btn pf-btn-ghost pf-btn-lg" onClick={() => store.nav('dashboard')}>Ir al inicio</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="pf-page" style={{ maxWidth: 880 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--muted)', marginBottom: 18, cursor: 'pointer' }} onClick={() => store.nav('property', p.id)}>
        <Icon name="chevright" size={14} style={{ transform: 'rotate(180deg)' }} /> Volver
      </div>
      <h1 style={{ fontSize: 26, marginBottom: 22 }}>Confirmar contratación</h1>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 20, alignItems: 'start' }}>
        {/* left: payment */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="pf-card" style={{ padding: 22 }}>
            <h3 style={{ fontSize: 16, marginBottom: 14 }}>Método de pago</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[['card', 'Tarjeta de crédito o débito', 'receipt'], ['spei', 'Transferencia SPEI', 'link'], ['oxxo', 'Pago en efectivo (OXXO)', 'pin']].map(([k, l, ic]) => (
                <div key={k} className={'pf-select-card' + (method === k ? ' on' : '')} onClick={() => setMethod(k)} style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
                  <span className="pf-radio">{method === k && <Icon name="check" size={13} style={{ color: '#1C1A17' }} />}</span>
                  <Icon name={ic} size={19} style={{ color: 'var(--muted)' }} />
                  <span style={{ fontSize: 14.5, fontWeight: 600, whiteSpace: 'nowrap' }}>{l}</span>
                </div>
              ))}
            </div>
            {method === 'card' && (
              <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div className="pf-field" style={{ margin: 0 }}>
                  <label>Número de tarjeta</label>
                  <input className="pf-input" placeholder="4242 4242 4242 4242" defaultValue="4242 4242 4242 4242" />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div className="pf-field" style={{ margin: 0 }}><label>Vencimiento</label><input className="pf-input" placeholder="MM/AA" defaultValue="08/28" /></div>
                  <div className="pf-field" style={{ margin: 0 }}><label>CVC</label><input className="pf-input" placeholder="123" defaultValue="123" /></div>
                </div>
              </div>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 12.5, color: 'var(--muted)', padding: '0 4px' }}>
            <Icon name="shield" size={15} style={{ color: 'var(--c-emerald)' }} /> Pago cifrado · Facturación CFDI automática
          </div>
        </div>

        {/* right: summary */}
        <div className="pf-card" style={{ padding: 22, position: 'sticky', top: 0 }}>
          <h3 style={{ fontSize: 15, marginBottom: 16 }}>Resumen</h3>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
            <span style={{ width: 44, height: 44, borderRadius: 11, background: p.thumb, flex: '0 0 auto' }} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
              <div className="pf-muted" style={{ fontSize: 12.5 }}>{p.alcaldia}</div>
            </div>
          </div>
          <div style={{ padding: '6px 0' }}>
            <div className="pf-summary-row"><span><span className="badge" style={{ background: STAGE_TONE[s.key][0], color: STAGE_TONE[s.key][1], marginRight: 6 }}>E{s.stage}</span>{s.name}</span><span className="pf-num" style={{ fontWeight: 600 }}>{mxn(price)}</span></div>
            <div className="pf-summary-row"><span className="pf-muted">IVA (16%)</span><span className="pf-num pf-muted">{mxn(iva)}</span></div>
          </div>
          <hr className="pf-divider" style={{ margin: '6px 0 14px' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
            <span style={{ fontWeight: 700, fontSize: 15 }}>Total</span>
            <span className="pf-num" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26 }}>{mxn(total)}</span>
          </div>
          <button className="pf-btn pf-btn-yellow pf-btn-lg" style={{ width: '100%' }} disabled={paying} onClick={pay}>
            {paying ? <><span className="pf-spin" /> Procesando…</> : <>Pagar {mxn(total)}</>}
          </button>
          <p style={{ fontSize: 11.5, color: 'var(--faint)', textAlign: 'center', marginTop: 12, lineHeight: 1.5 }}>{s.range ? 'El precio final de gestión se confirma según la complejidad del trámite.' : 'Pago único por este inmueble. Sin renovación automática.'}</p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Services, Checkout });
