// KineSuite landing — comparison table + roadmap notify form.

const { useState: useNotifyS } = React;

function CompStatusIcon({ kind }) {
  const map = {
    yes:     { glyph: '✓', color: 'var(--semantic-green)', bg: 'var(--semantic-green-bg)' },
    partial: { glyph: '~', color: 'var(--semantic-yellow)', bg: 'var(--semantic-yellow-bg)' },
    no:      { glyph: '×', color: 'var(--semantic-red)', bg: 'var(--semantic-red-bg)' },
  };
  const s = map[kind] || map.no;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 22, height: 22, borderRadius: 6,
      background: s.bg, color: s.color,
      fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 12,
    }}>
      {s.glyph}
    </span>
  );
}

function CompHeaderCell({ name, muted, highlight }) {
  return (
    <div style={{
      padding: '20px 24px',
      background: highlight ? 'var(--primary)' : muted ? 'var(--gray-050)' : 'var(--paper)',
      borderBottom: '1px solid var(--gray-200)',
      color: highlight ? '#fff' : 'var(--gray-700)',
    }}>
      <div className="eyebrow" style={{ color: highlight ? 'rgba(255,255,255,0.75)' : undefined }}>
        {name}
      </div>
    </div>
  );
}

function CompareMobileCard({ row, t }) {
  const cols = [
    { key: 'paper', label: t.compareColPaper },
    { key: 'excel', label: t.compareColExcel },
    { key: 'ks', label: 'KineSuite', highlight: true },
  ];
  return (
    <article className="compare-mobile-card">
      <h3>{row.label}</h3>
      {cols.map(({ key, label, highlight }) => {
        const cell = row[key];
        return (
          <div
            key={key}
            className={highlight ? 'compare-mobile-row compare-mobile-row--ks' : 'compare-mobile-row'}
          >
            <span className="compare-mobile-label">{label}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
              <CompStatusIcon kind={cell.kind} />
              {cell.label && (
                <span style={{
                  fontSize: 13,
                  color: highlight ? 'var(--ink)' : 'var(--gray-700)',
                  fontWeight: highlight ? 600 : 400,
                }}>
                  {cell.label}
                </span>
              )}
            </div>
          </div>
        );
      })}
    </article>
  );
}

function ComparisonSection({ t }) {
  const rows = t.compareRows;
  return (
    <section id="comparativa" style={{ background: 'var(--bone)' }}>
      <div className="container">
        <div className="section-intro">
          <Eyebrow>{t.compareEyebrow}</Eyebrow>
          <h2 className="section-title">{t.compareTitle}</h2>
          <p className="lead">{t.compareSub}</p>
        </div>

        <div className="compare-desktop compare-table">
          <div style={{ padding: '20px 24px', background: 'var(--gray-050)', borderBottom: '1px solid var(--gray-200)' }}>
            <div className="eyebrow">{t.compareCriterion}</div>
          </div>
          <CompHeaderCell name={t.compareColPaper} muted />
          <CompHeaderCell name={t.compareColExcel} muted />
          <CompHeaderCell name="KineSuite" highlight />

          {rows.map((row, i) => {
            const last = i === rows.length - 1;
            const border = last ? 'none' : '1px solid var(--gray-200)';
            return (
              <React.Fragment key={i}>
                <div style={{
                  padding: '22px 24px', borderBottom: border,
                  display: 'flex', flexDirection: 'column', gap: 4,
                }}>
                  <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{row.label}</div>
                </div>
                <div style={{ padding: '22px 24px', borderBottom: border, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <CompStatusIcon kind={row.paper.kind} />
                  {row.paper.label && <span style={{ fontSize: 13, color: 'var(--gray-700)' }}>{row.paper.label}</span>}
                </div>
                <div style={{ padding: '22px 24px', borderBottom: border, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <CompStatusIcon kind={row.excel.kind} />
                  {row.excel.label && <span style={{ fontSize: 13, color: 'var(--gray-700)' }}>{row.excel.label}</span>}
                </div>
                <div style={{
                  padding: '22px 24px', borderBottom: border,
                  background: 'var(--primary-050)',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                  <CompStatusIcon kind={row.ks.kind} />
                  {row.ks.label && <span style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 600 }}>{row.ks.label}</span>}
                </div>
              </React.Fragment>
            );
          })}
        </div>

        <div className="compare-mobile" role="list">
          {rows.map((row, i) => (
            <CompareMobileCard key={i} row={row} t={t} />
          ))}
        </div>

        <p style={{ marginTop: 24, fontSize: 13, color: 'var(--gray-500)', maxWidth: '70ch' }}>
          {t.compareFootnote}
        </p>
      </div>
    </section>
  );
}

// Replace FORMSPREE_ID with your Formspree form ID (https://formspree.io → new form → copy the id)
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/mbdbdzgl';

function PriorityChip({ label, checked, disabled, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '7px 13px',
        borderRadius: 999,
        border: `1.5px solid ${checked ? 'var(--primary)' : 'var(--gray-300)'}`,
        background: checked ? 'var(--primary-100)' : 'var(--paper)',
        color: checked ? 'var(--primary)' : disabled ? 'var(--gray-400)' : 'var(--gray-700)',
        fontSize: 13,
        fontWeight: checked ? 600 : 400,
        fontFamily: 'inherit',
        cursor: disabled ? 'default' : 'pointer',
        opacity: disabled ? 0.45 : 1,
        transition: 'border-color 0.15s, background 0.15s, color 0.15s',
        lineHeight: 1.3,
      }}
    >
      {checked && (
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden="true">
          <path d="M1.5 5l2.5 2.5 4.5-5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      )}
      {label}
    </button>
  );
}

function NotifySection({ t }) {
  const [email, setEmail] = useNotifyS('');
  const [priorities, setPriorities] = useNotifyS([]);
  const [specialty, setSpecialty] = useNotifyS('');
  const [missingScale, setMissingScale] = useNotifyS('');
  const [done, setDone] = useNotifyS(false);
  const [error, setError] = useNotifyS(false);
  const [sending, setSending] = useNotifyS(false);

  const MAX = 3;

  const togglePriority = (id) => {
    setPriorities((prev) => {
      if (prev.includes(id)) return prev.filter((x) => x !== id);
      if (prev.length >= MAX) return prev;
      return [...prev, id];
    });
  };

  const reset = () => {
    setDone(false); setEmail(''); setPriorities([]);
    setSpecialty(''); setMissingScale('');
  };

  const submit = async (e) => {
    e.preventDefault();
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setError(true); return; }
    setError(false);
    setSending(true);
    const payload = {
      email: email.trim(),
      prioridades: priorities.join(', ') || '—',
      especialidad: specialty || '—',
      escala_faltante: missingScale.trim() || '—',
    };
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error('network');
    } catch {
      try {
        localStorage.setItem('kinesuite-notify', JSON.stringify({ ...payload, at: Date.now() }));
      } catch {}
    } finally {
      setSending(false);
    }
    setDone(true);
  };

  return (
    <section id="notify">
      <div className="container" style={{ maxWidth: 620 }}>
        <Eyebrow>{t.notifyEyebrow}</Eyebrow>
        <h2 className="section-title">{t.notifyTitle}</h2>
        <p className="lead" style={{ marginBottom: 32 }}>{t.notifySub}</p>

        {done ? (
          <div className="card" style={{ padding: 28 }}>
            <h3 style={{ fontSize: 22, marginBottom: 8 }}>{t.notifyDoneTitle}</h3>
            <p>{t.notifyDoneBody}</p>
            <button type="button" className="btn btn-ghost" style={{ marginTop: 16 }} onClick={reset}>
              {t.notifyAnother}
            </button>
          </div>
        ) : (
          <form className="card" style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 24 }} onSubmit={submit}>

            {/* ── Email ── */}
            <label style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
              {t.notifyEmailLabel}
              <input
                type="email"
                value={email}
                onChange={(e) => { setEmail(e.target.value); if (error) setError(false); }}
                placeholder={t.notifyEmailPlaceholder}
                style={{
                  padding: '12px 14px', borderRadius: 10,
                  border: `1px solid ${error ? 'var(--semantic-red)' : 'var(--gray-300)'}`,
                  fontSize: 15, fontFamily: 'inherit',
                  color: 'var(--ink)', background: 'var(--paper)',
                }}
              />
              {error && (
                <span style={{ color: 'var(--semantic-red)', fontSize: 13, fontWeight: 400 }}>
                  {t.notifyError}
                </span>
              )}
            </label>

            {/* ── Priority chips (grouped) ── */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{t.notifyMaxHint}</span>
                <span style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.08em',
                  color: priorities.length >= MAX ? 'var(--primary)' : 'var(--gray-400)',
                }}>
                  {priorities.length}/{MAX}
                </span>
              </div>

              {t.notifyGroups.map((group) => (
                <div key={group.id} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <div style={{
                    fontFamily: 'JetBrains Mono, monospace',
                    fontSize: 9.5, fontWeight: 600,
                    letterSpacing: '0.12em', textTransform: 'uppercase',
                    color: 'var(--gray-400)',
                    paddingBottom: 6,
                    borderBottom: '1px solid var(--gray-200)',
                  }}>
                    {group.label}
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {group.items.map((item) => {
                      const checked = priorities.includes(item.id);
                      const disabled = !checked && priorities.length >= MAX;
                      return (
                        <PriorityChip
                          key={item.id}
                          label={item.label}
                          checked={checked}
                          disabled={disabled}
                          onClick={() => togglePriority(item.id)}
                        />
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>

            {/* ── Specialty ── */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{t.notifySpecialtyLabel}</span>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {t.notifySpecialtyOptions.map((opt) => {
                  const active = specialty === opt;
                  return (
                    <button
                      key={opt}
                      type="button"
                      onClick={() => setSpecialty(active ? '' : opt)}
                      style={{
                        padding: '7px 13px', borderRadius: 999,
                        border: `1.5px solid ${active ? 'var(--primary)' : 'var(--gray-300)'}`,
                        background: active ? 'var(--primary-100)' : 'var(--paper)',
                        color: active ? 'var(--primary)' : 'var(--gray-700)',
                        fontSize: 13, fontWeight: active ? 600 : 400,
                        fontFamily: 'inherit', cursor: 'pointer',
                        transition: 'border-color 0.15s, background 0.15s',
                      }}
                    >
                      {opt}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* ── Missing scale ── */}
            <label style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
              {t.notifyScaleInputLabel}
              <input
                type="text"
                value={missingScale}
                onChange={(e) => setMissingScale(e.target.value.slice(0, 120))}
                placeholder={t.notifyScaleInputPlaceholder}
                style={{
                  padding: '12px 14px', borderRadius: 10,
                  border: '1px solid var(--gray-300)',
                  fontSize: 15, fontFamily: 'inherit',
                  color: 'var(--ink)', background: 'var(--paper)',
                }}
              />
            </label>

            <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }} disabled={sending}>
              {sending ? '…' : t.notifyCta}
            </button>
            <p style={{ fontSize: 12, color: 'var(--gray-500)', margin: 0 }}>{t.notifyFinePrint}</p>
            <p style={{ fontSize: 12, color: 'var(--gray-400)', margin: 0, fontFamily: 'JetBrains Mono, monospace' }}>
              {t.notifyTrustNoSpam}
            </p>
          </form>
        )}
      </div>
    </section>
  );
}

Object.assign(window, {
  ComparisonSection, NotifySection,
});
