// ============================================================
// SECTIONS — Steps, Features, Compare, CTA, Footer
// ============================================================

const CG_ICONS = {
  scan:    <><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="12" cy="11" r="3"/><path d="M7 20v-1a5 5 0 0110 0v1"/></>,
  grid:    <><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 3v18"/></>,
  mail:    <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></>,
  cal:     <><rect x="3" y="5" width="18" height="16" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="8" y1="3" x2="8" y2="7"/><line x1="16" y1="3" x2="16" y2="7"/></>,
  send:    <><path d="M4 11l16-7-7 16-2-7z"/></>,
  export:  <><path d="M12 3v12M8 11l4 4 4-4"/><path d="M5 21h14"/></>,
  offline: <><path d="M5 12.5a7.5 7.5 0 0115 0"/><circle cx="12" cy="13" r="2"/></>,
  clock:   <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></>,
  log:     <><path d="M4 6h16M4 12h16M4 18h10"/><circle cx="20" cy="18" r="2"/></>,
};

// ============================================================
// WAITLIST API CONFIG (CTA form, Section G)
// ============================================================
// Production endpoint. To test against `wrangler dev` locally, change this
// to "http://127.0.0.1:8787/api/waitlist" — and revert before committing.
const WAITLIST_API_URL = "https://api.cardgap.app/api/waitlist";

const WAITLIST_ERRORS = {
  alreadyOnList: "You're already on the waitlist. Check your inbox for the confirmation email.",
  invalidEmail:  "Please enter a valid email address.",
  emailFailure:  "We saved your spot, but the confirmation email did not go out. Please contact hello@cardgap.app.",
  generic:       "Something went wrong, please try again in a moment.",
};

function Steps() {
  const s = CG.steps;
  return (
    <section id="steps" style={{ padding: '100px 56px', maxWidth: 1200, margin: '0 auto' }}>
      <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: 44, fontWeight: 400, letterSpacing: -0.8, lineHeight: 1.06, margin: 0, whiteSpace: 'pre-line' }}>
        {s.title.split('\n').map((l, i) => i === 1 ? <em key={i} style={{ color: '#3E5340', fontStyle: 'italic' }}>{l}</em> : <span key={i}>{l}<br/></span>)}
      </h2>
      <p style={{ fontSize: 16, color: '#55584B', maxWidth: 580, marginTop: 18, lineHeight: 1.55 }}>{s.sub}</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 0, marginTop: 50, borderTop: '1px solid #D6D0B3', borderLeft: '1px solid #D6D0B3' }}>
        {s.items.map(it => (
          <div key={it.title} style={{ padding: '32px 30px', borderRight: '1px solid #D6D0B3', borderBottom: '1px solid #D6D0B3', background: '#FBF7EA' }}>
            <div style={{ fontFamily: "'Fraunces', serif", fontSize: 24, fontWeight: 500, margin: '0 0 8px', letterSpacing: -0.3 }}>{it.title}</div>
            <p style={{ fontSize: 13.5, color: '#55584B', lineHeight: 1.6, margin: 0 }}>{it.body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function Surfaces() {
  const s = CG.surfaces;
  return (
    <section id="surfaces" style={{ padding: '100px 56px', maxWidth: 1200, margin: '0 auto' }}>
      <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: 44, fontWeight: 400, letterSpacing: -0.8, lineHeight: 1.06, margin: 0 }}>{s.title}</h2>
      <p style={{ fontSize: 16, color: '#55584B', maxWidth: 720, marginTop: 18, lineHeight: 1.55 }}>{s.sub}</p>
      <div style={{ marginTop: 44, border: '1px solid #D6D0B3', borderRadius: 6, background: '#FBF7EA', overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', borderBottom: '1px solid #D6D0B3' }}>
          {s.columns.map((col, i) => (
            <div key={col.title} style={{ padding: '32px 30px', borderRight: i === 0 ? '1px solid #D6D0B3' : 'none' }}>
              <div style={{ fontFamily: "'Fraunces', serif", fontSize: 22, fontWeight: 500, margin: '0 0 14px', letterSpacing: -0.3, color: '#1F2418' }}>{col.title}</div>
              <p style={{ fontSize: 13.5, color: '#55584B', lineHeight: 1.6, margin: 0 }}>{col.body}</p>
            </div>
          ))}
        </div>
        <div style={{ padding: '14px 30px', display: 'flex', alignItems: 'center', gap: 10, fontFamily: "'Inter', sans-serif", fontSize: 13, fontWeight: 500, color: '#1F2418', background: 'rgba(181,160,78,0.06)' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#B5A04E', flexShrink: 0 }}></span>
          {s.footerLine}
        </div>
      </div>
    </section>
  );
}

function Features() {
  const f = CG.features;
  return (
    <section id="features" style={{ padding: '100px 56px', maxWidth: 1200, margin: '0 auto', background: '#F4EFDE', borderRadius: 8 }}>
      <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: 40, fontWeight: 400, letterSpacing: -0.7, margin: 0 }}>{f.title}</h2>
      <p style={{ fontSize: 16, color: '#55584B', maxWidth: 600, marginTop: 16, lineHeight: 1.55 }}>{f.sub}</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 28, marginTop: 44 }}>
        {f.items.map(it => (
          <div key={it.title} style={{ background: '#FBF7EA', border: '1px solid #D6D0B3', borderRadius: 6, padding: '22px 22px 24px' }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#3E5340" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">{CG_ICONS[it.icon]}</svg>
            <div style={{ fontFamily: "'Fraunces', serif", fontSize: 18, fontWeight: 500, margin: '12px 0 6px' }}>{it.title}</div>
            <p style={{ fontSize: 13, color: '#55584B', lineHeight: 1.55, margin: 0 }}>{it.body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function Compare() {
  const c = CG.compare;
  const cell = v => {
    if (v === '✓') return <span style={{ color: '#3E5340', fontSize: 18 }}>✓</span>;
    if (v === '✗') return <span style={{ color: '#B94A3A', fontSize: 16 }}>✗</span>;
    if (v === 'partial') return <span style={{ fontSize: 10, color: '#8A7A3E', fontFamily: "'JetBrains Mono', monospace", letterSpacing: 1, textTransform: 'uppercase' }}>partial</span>;
    if (v === 'One-time') return <span style={{ background: '#3E5340', color: '#F2ECD4', padding: '3px 10px', borderRadius: 3, fontSize: 11, fontWeight: 600 }}>One-time</span>;
    return <span style={{ color: '#55584B', fontSize: 13 }}>{v}</span>;
  };
  return (
    <section id="compare" style={{ padding: '100px 56px', maxWidth: 1200, margin: '0 auto' }}>
      <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: 40, fontWeight: 400, letterSpacing: -0.7, margin: 0 }}>{c.title}</h2>
      <p style={{ fontSize: 16, color: '#55584B', maxWidth: 560, marginTop: 14, lineHeight: 1.55 }}>{c.sub}</p>
      <div style={{ marginTop: 36, background: '#FBF7EA', border: '1px solid #D6D0B3', borderRadius: 6, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: "'Inter', sans-serif" }}>
          <thead>
            <tr style={{ background: '#EFE7CA' }}>
              {c.columns.map((col, i) => (
                <th key={col} style={{
                  padding: '14px 18px', fontSize: 12, letterSpacing: 1.5, textTransform: 'uppercase',
                  color: i === 1 ? '#3E5340' : '#6B6A52', textAlign: i === 0 ? 'left' : 'center',
                  borderBottom: '1px solid #D6D0B3', fontWeight: 600,
                }}>{col}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {c.rows.map((r, ri) => (
              <tr key={ri} style={{ background: ri % 2 ? '#F7F1DE' : 'transparent' }}>
                {r.map((v, ci) => (
                  <td key={ci} style={{
                    padding: '14px 18px', fontSize: 13, color: '#2B2A1E',
                    textAlign: ci === 0 ? 'left' : 'center',
                    borderBottom: ri < c.rows.length - 1 ? '1px solid #E8E0C0' : 'none',
                    fontWeight: ci === 0 ? 500 : 400,
                    background: ci === 1 ? 'rgba(181,160,78,0.08)' : 'transparent',
                  }}>{ci === 0 ? v : cell(v)}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

function CTA() {
  const c = CG.cta;
  const [email, setEmail]       = React.useState("");
  const [status, setStatus]     = React.useState("idle"); // idle | submitting | success | error
  const [errorMsg, setErrorMsg] = React.useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    if (status === "submitting") return;
    setStatus("submitting");
    setErrorMsg("");
    try {
      const r = await fetch(WAITLIST_API_URL, {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ email, source: "cardgap-site-cta" }),
      });
      if (r.ok) {
        setStatus("success");
        setEmail("");
        return;
      }
      let msg = WAITLIST_ERRORS.generic;
      if      (r.status === 409) msg = WAITLIST_ERRORS.alreadyOnList;
      else if (r.status === 400) msg = WAITLIST_ERRORS.invalidEmail;
      else if (r.status === 502) msg = WAITLIST_ERRORS.emailFailure;
      setStatus("error");
      setErrorMsg(msg);
    } catch (_err) {
      setStatus("error");
      setErrorMsg(WAITLIST_ERRORS.generic);
    }
  }

  const submitting = status === "submitting";

  return (
    <section id="cta" style={{ padding: '100px 56px', textAlign: 'center', background: '#2F4232', color: '#F2ECD4', margin: '80px 16px 0', borderRadius: 18 }}>
      <div style={{ maxWidth: 720, margin: '0 auto' }}>
        <div style={{ display: 'inline-block', fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', color: '#C9B36F', padding: '5px 12px', border: '1px solid #C9B36F', borderRadius: 2, marginBottom: 28 }}>{c.eyebrow}</div>
        <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: 48, fontWeight: 400, letterSpacing: -0.9, lineHeight: 1.05, margin: 0, whiteSpace: 'pre-line' }}>
          {c.headline.split('\n').map((l, i) => i === 1 ? <em key={i} style={{ color: '#C9B36F', fontStyle: 'italic' }}>{l}</em> : <span key={i}>{l}<br/></span>)}
        </h2>
        <p style={{ fontSize: 15, color: '#C7BFA0', maxWidth: 560, margin: '20px auto 0', lineHeight: 1.6 }}>{c.body}</p>
        <div style={{ display: 'flex', gap: 24, justifyContent: 'center', marginTop: 22, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: 1.5, color: '#C9B36F' }}>
          <span>{c.priceInstall} install</span><span style={{ color: '#6B7560' }}>·</span><span>{c.priceAnnual}</span>
        </div>

        {status === "success" ? (
          <div style={{
            maxWidth: 520, margin: '36px auto 12px',
            padding: '18px 24px',
            border: '1px solid rgba(201,179,111,0.45)',
            borderRadius: 4,
            background: 'rgba(181,160,78,0.08)',
            fontFamily: "'Inter', sans-serif",
            fontSize: 14,
            lineHeight: 1.55,
            color: '#F2ECD4',
          }} aria-live="polite">
            <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: '#C9B36F', marginRight: 10, verticalAlign: 'middle' }} />
            {c.successMessage}
          </div>
        ) : (
          <>
            <form
              onSubmit={handleSubmit}
              style={{ display: 'flex', gap: 8, maxWidth: 480, margin: '36px auto 12px' }}
              noValidate
            >
              <input
                type="email"
                required
                placeholder={c.formPlaceholder}
                value={email}
                onChange={e => setEmail(e.target.value)}
                disabled={submitting}
                aria-invalid={status === 'error'}
                style={{
                  flex: 1, padding: '12px 16px', background: 'rgba(255,255,255,0.08)',
                  border: '1px solid rgba(201,179,111,0.35)', borderRadius: 4,
                  color: '#F2ECD4', fontSize: 14, fontFamily: "'Inter', sans-serif", outline: 'none',
                  opacity: submitting ? 0.7 : 1,
                }}
              />
              <button
                type="submit"
                disabled={submitting}
                style={{
                  background: '#B5A04E', color: '#1F2012', border: 'none', padding: '12px 22px',
                  borderRadius: 4, fontSize: 14, fontWeight: 600, cursor: submitting ? 'wait' : 'pointer',
                  fontFamily: "'Inter', sans-serif", opacity: submitting ? 0.7 : 1,
                  minWidth: 130,
                }}
              >{submitting ? 'Sending…' : c.submitLabel}</button>
            </form>
            {status === "error" ? (
              <div role="alert" style={{
                fontFamily: "'Inter', sans-serif", fontSize: 13,
                color: '#F2D9C0', lineHeight: 1.5, maxWidth: 520, margin: '0 auto',
              }}>{errorMsg}</div>
            ) : (
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, color: '#9FA984', letterSpacing: 1 }}>{c.fine}</div>
            )}
          </>
        )}
      </div>
    </section>
  );
}

function Footer() {
  const f = CG.footer;
  return (
    <footer style={{
      padding: '32px 56px 28px', margin: '0 16px 16px',
      background: '#EFE7CA', borderRadius: '0 0 18px 18px',
      borderTop: '1px solid #D6D0B3',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
        gap: 32, flexWrap: 'wrap',
      }}>
        <div>
          <div style={{ fontFamily: "'Fraunces', serif", fontSize: 22, fontWeight: 500, color: '#2B2A1E', letterSpacing: -0.2 }}>{f.brand}</div>
          <nav style={{ display: 'flex', flexWrap: 'wrap', gap: 18, marginTop: 14, fontSize: 12.5, fontWeight: 500 }}>
            {f.links.map(l => (
              <a key={l.label} href={l.href} style={{ color: '#5E6358', textDecoration: 'none' }}>{l.label}</a>
            ))}
          </nav>
        </div>
        <address style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 10.5, lineHeight: 1.7, letterSpacing: 0.02,
          color: '#5E6358', textAlign: 'right', fontStyle: 'normal',
        }}>
          <div>{f.copyright}</div>
          <div>
            <a href={`mailto:${f.email}`} style={{ color: '#5E6358', textDecoration: 'none', borderBottom: '1px solid #B5A04E', paddingBottom: 1 }}>{f.email}</a>
          </div>
        </address>
      </div>
    </footer>
  );
}

window.Steps = Steps;
window.Surfaces = Surfaces;
window.Features = Features;
window.Compare = Compare;
window.CTA = CTA;
window.Footer = Footer;
