/* global React */
// About, Certifications, Contact pages + ContactForm

function AboutPage({ t, navigate }) {
  const a = t.about;
  return (
    <main className="page-enter">
      <section className="section" style={{ paddingTop: 180, paddingBottom: 80 }}>
        <div className="container">
          <div className="eyebrow">{a.eyebrow}</div>
          <h1 className="h-display" style={{ margin: '16px 0 48px', whiteSpace: 'pre-line' }}>{a.title}</h1>
          <p className="body-lg" style={{ fontSize: 19, maxWidth: '68ch' }}>{a.sub}</p>
        </div>
      </section>

      {/* Principles */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow">{a.principlesEyebrow}</div>
              <h2 className="h-xl" style={{ margin: '12px 0 0' }}>{a.principlesTitle}</h2>
            </div>
            <div/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 0, border: '1px solid var(--line)' }} className="princ-grid">
            {a.principles.map((p, i) => (
              <div key={i} style={{
                padding: 48,
                borderRight: i % 2 === 0 ? '1px solid var(--line)' : 'none',
                borderBottom: i < 2 ? '1px solid var(--line)' : 'none',
                display: 'flex', flexDirection: 'column', gap: 16,
              }}>
                <div className="mono-sm" style={{ color: 'var(--accent)' }}>{p.n}</div>
                <h3 className="h-lg" style={{ margin: 0 }}>{p.k}</h3>
                <p style={{ color: 'var(--fg-1)', fontSize: 15, lineHeight: 1.6, maxWidth: '48ch', margin: 0 }}>{p.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Team block */}
      <section className="section" style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)' }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'center' }} className="team-grid">
            <div>
              <div className="eyebrow">{a.teamEyebrow}</div>
              <h2 className="h-xl" style={{ margin: '12px 0 24px' }}>{a.teamTitle}</h2>
              <p className="body-lg">{a.teamSub}</p>
            </div>
            <TeamGrid/>
          </div>
        </div>
      </section>

      {/* Timeline */}
      <section className="section">
        <div className="container">
          <div className="eyebrow">{a.timelineEyebrow}</div>
          <div style={{ marginTop: 48, borderTop: '1px solid var(--line)' }}>
            {a.timeline.map((ev, i) => (
              <div key={i} style={{
                display: 'grid',
                gridTemplateColumns: '140px 200px 1fr',
                gap: 32,
                padding: '32px 0',
                borderBottom: '1px solid var(--line)',
                alignItems: 'baseline',
              }} className="tl-row">
                <span style={{
                  fontFamily: 'var(--ff-display)', fontSize: 36, letterSpacing: '-0.02em',
                  color: i === t.about.timeline.length - 1 ? 'var(--accent)' : 'var(--fg-0)',
                }}>{ev.y}</span>
                <span className="h-md">{ev.k}</span>
                <span style={{ color: 'var(--fg-2)', fontSize: 15 }}>{ev.d}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      <FinalCTA t={t} navigate={navigate}/>
    </main>
  );
}

function TeamGrid() {
  // 14 abstract operator avatars (CSS placeholder tiles)
  const tiles = Array.from({ length: 14 }).map((_, i) => {
    const hue = 230 + ((i * 13) % 20);
    const t = ['OS', 'MR', 'KV', 'JL', 'AP', 'DS', 'FC', 'NM', 'TB', 'ER', 'IG', 'LV', 'CP', 'RS'][i];
    return { t, hue };
  });
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(7, 1fr)',
      gap: 4,
    }}>
      {tiles.map((tile, i) => (
        <div key={i} style={{
          aspectRatio: '1 / 1',
          background: `oklch(0.${20 + (i % 4) * 2} 0.01 ${tile.hue})`,
          border: '1px solid var(--line)',
          display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--ff-mono)',
          fontSize: 13,
          letterSpacing: '0.04em',
          color: 'var(--fg-2)',
          position: 'relative',
          overflow: 'hidden',
        }}>
          <span>{tile.t}</span>
          <span style={{
            position: 'absolute', bottom: 4, right: 4,
            width: 6, height: 6,
            background: 'var(--accent)',
            opacity: i % 3 === 0 ? 1 : 0.3,
          }}/>
        </div>
      ))}
    </div>
  );
}

// ── Certifications page ──────────────────────────────────────
function CertificationsPage({ t, navigate }) {
  const c = t.certifications;
  return (
    <main className="page-enter">
      <section className="section" style={{ paddingTop: 180 }}>
        <div className="container">
          <div className="eyebrow">{c.eyebrow}</div>
          <h1 className="h-display" style={{ margin: '16px 0 32px', fontSize: 'clamp(40px, 5vw, 72px)' }}>{c.title}</h1>
          <p className="body-lg" style={{ maxWidth: '64ch' }}>{c.sub}</p>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 40 }}>
        <div className="container">
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, 1fr)',
            gap: 1,
            background: 'var(--line)',
            border: '1px solid var(--line)',
          }} className="certs-full">
            {c.items.map((it, i) => (
              <div key={i} style={{
                background: 'var(--bg-0)',
                padding: '32px 36px',
                display: 'grid',
                gridTemplateColumns: '120px 1fr 160px',
                gap: 24,
                alignItems: 'center',
                transition: 'background var(--t-fast)',
              }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-1)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'var(--bg-0)'}>
                <div style={{
                  fontFamily: 'var(--ff-display)',
                  fontSize: 26,
                  letterSpacing: '-0.01em',
                  color: 'var(--accent)',
                }}>{it.k}</div>
                <div style={{ color: 'var(--fg-1)', fontSize: 14 }}>{it.d}</div>
                <div className="mono-sm" style={{ color: 'var(--fg-3)', textAlign: 'right' }}>· {it.c}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="eyebrow">{c.complianceEyebrow}</div>
          <div style={{ marginTop: 32, display: 'flex', flexWrap: 'wrap', gap: 12 }}>
            {c.compliance.map((cp, i) => (
              <span key={i} style={{
                padding: '14px 22px',
                border: '1px solid var(--line)',
                fontFamily: 'var(--ff-mono)',
                fontSize: 13,
                letterSpacing: '0.05em',
                color: 'var(--fg-1)',
              }}>{cp}</span>
            ))}
          </div>
        </div>
      </section>

      <FinalCTA t={t} navigate={navigate}/>
    </main>
  );
}

// ── Contact page ────────────────────────────────────────────
function ContactPage({ t }) {
  const c = t.contact;
  return (
    <main className="page-enter">
      <section className="section" style={{ paddingTop: 180, paddingBottom: 48 }}>
        <div className="container">
          <div className="eyebrow">{c.eyebrow}</div>
          <h1 className="h-display" style={{ margin: '16px 0 32px', whiteSpace: 'pre-line', fontSize: 'clamp(40px, 5.5vw, 84px)' }}>{c.title}</h1>
          <p className="body-lg" style={{ maxWidth: '62ch' }}>{c.sub}</p>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 40, paddingBottom: 120 }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48, alignItems: 'start' }} className="contact-grid">
            <ContactForm t={t}/>
            <ContactSidebar t={t}/>
          </div>
        </div>
      </section>
    </main>
  );
}

// ── Contact form (reusable, with validation + states) ───────
function ContactForm({ t, compact = false }) {
  const f = t.contact.form;
  const [values, setValues] = useState({
    name: '', email: '', company: '', phone: '', service: '', message: '',
  });
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState('idle'); // idle | submitting | success | error

  const setField = (k, v) => {
    setValues((o) => ({ ...o, [k]: v }));
    if (errors[k]) setErrors((e) => ({ ...e, [k]: null }));
  };

  const validate = () => {
    const e = {};
    if (!values.name.trim()) e.name = f.required;
    if (!values.email.trim()) e.email = f.required;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) e.email = f.invalidEmail;
    if (!values.company.trim()) e.company = f.required;
    if (!values.message.trim()) e.message = f.required;
    return e;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setStatus('submitting');
    try {
      const resp = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: values.name.trim(),
          email: values.email.trim(),
          company: values.company.trim(),
          phone: values.phone.trim() || null,
          service: values.service || null,
          message: values.message.trim(),
        }),
      });
      setStatus(resp.ok ? 'success' : 'error');
    } catch {
      setStatus('error');
    }
  };

  const reset = () => {
    setValues({ name: '', email: '', company: '', phone: '', service: '', message: '' });
    setErrors({});
    setStatus('idle');
  };

  return (
    <div style={{
      border: '1px solid var(--line)',
      background: 'var(--bg-1)',
      padding: compact ? 40 : 48,
      position: 'relative',
    }} className="corners">
      <span className="tl"/><span className="br"/>

      {compact && (
        <>
          <div className="eyebrow" style={{ marginBottom: 16 }}>{t.contact.eyebrow}</div>
          <h2 className="h-xl" style={{ margin: '0 0 16px', fontSize: 'clamp(28px, 3vw, 40px)' }}>
            {t.contact.title}
          </h2>
          <p style={{ color: 'var(--fg-1)', margin: '0 0 32px', maxWidth: '60ch' }}>{t.contact.sub}</p>
        </>
      )}

      {status === 'success' ? (
        <SuccessState t={t} onReset={reset}/>
      ) : (
        <form onSubmit={onSubmit} noValidate style={{ display: 'grid', gap: 20 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }} className="form-row">
            <FormField label={f.name} value={values.name} err={errors.name}
              placeholder={f.namePh} onChange={(v) => setField('name', v)} required/>
            <FormField label={f.email} value={values.email} err={errors.email} type="email"
              placeholder={f.emailPh} onChange={(v) => setField('email', v)} required/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }} className="form-row">
            <FormField label={f.company} value={values.company} err={errors.company}
              placeholder={f.companyPh} onChange={(v) => setField('company', v)} required/>
            <FormField label={f.phone} value={values.phone} err={errors.phone} type="tel"
              placeholder={f.phonePh} onChange={(v) => setField('phone', v)}/>
          </div>

          <div className="field">
            <label>{f.service}</label>
            <select value={values.service} onChange={(e) => setField('service', e.target.value)}>
              <option value="">{f.servicePh}</option>
              {f.serviceOptions.map((opt, i) => (
                <option key={i} value={opt}>{opt}</option>
              ))}
            </select>
          </div>

          <div className={`field ${errors.message ? 'has-error' : ''}`}>
            <label>
              <span>{f.message} <span className="req">*</span></span>
              {errors.message && <span className="err">{errors.message}</span>}
            </label>
            <textarea rows={5} value={values.message}
              placeholder={f.messagePh}
              onChange={(e) => setField('message', e.target.value)}/>
          </div>

          {status === 'error' && (
            <div style={{
              padding: 14, border: '1px solid var(--danger)',
              color: 'var(--danger)',
              fontFamily: 'var(--ff-mono)', fontSize: 12, letterSpacing: '0.04em',
            }}>✕ {f.error}</div>
          )}

          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            gap: 20, flexWrap: 'wrap',
            borderTop: '1px solid var(--line)', paddingTop: 24,
          }}>
            <span className="mono-sm" style={{ color: 'var(--fg-3)', maxWidth: '44ch' }}>
              {f.consent}
            </span>
            <button type="submit" className="btn btn-primary" disabled={status === 'submitting'}
              style={{ opacity: status === 'submitting' ? 0.6 : 1, cursor: status === 'submitting' ? 'wait' : 'pointer' }}>
              {status === 'submitting' ? (
                <>
                  <span className="spinner"/>
                  {f.submitting}
                </>
              ) : (
                <>{f.submit} <span className="arrow">→</span></>
              )}
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

function FormField({ label, value, err, onChange, placeholder, required, type = 'text' }) {
  return (
    <div className={`field ${err ? 'has-error' : ''}`}>
      <label>
        <span>{label} {required && <span className="req">*</span>}</span>
        {err && <span className="err">{err}</span>}
      </label>
      <input type={type} value={value} placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)} />
    </div>
  );
}

function SuccessState({ t, onReset }) {
  const f = t.contact.form;
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      padding: '60px 20px', textAlign: 'center', gap: 20,
    }}>
      <div style={{
        width: 64, height: 64,
        border: '1px solid var(--accent)',
        display: 'grid', placeItems: 'center',
      }}>
        <svg width="28" height="28" viewBox="0 0 28 28">
          <path d="M6 14 L12 20 L22 8" stroke="var(--accent)" strokeWidth="2" fill="none"/>
        </svg>
      </div>
      <h3 className="h-lg" style={{ margin: 0 }}>{f.success}</h3>
      <p className="mono-sm" style={{ color: 'var(--fg-3)' }}>
        TICKET-{Math.random().toString(36).slice(2, 8).toUpperCase()} · QUEUED
      </p>
      <button className="btn" onClick={onReset} style={{ marginTop: 16 }}>New request</button>
    </div>
  );
}

function ContactSidebar({ t }) {
  const c = t.contact;
  return (
    <aside style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
      <div style={{ padding: 32, border: '1px solid var(--line)', background: 'var(--bg-0)' }}>
        <div className="eyebrow" style={{ marginBottom: 20 }}>{c.directEyebrow}</div>
        <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {c.direct.map((d, i) => (
            <li key={i} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <span className="mono-sm" style={{ color: 'var(--fg-3)' }}>{d.k}</span>
              <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 14, color: 'var(--fg-0)' }}>{d.v}</span>
            </li>
          ))}
        </ul>
      </div>
      <div style={{ padding: 32, border: '1px solid var(--line)', background: 'var(--bg-0)' }}>
        <div className="eyebrow" style={{ marginBottom: 16 }}>PGP</div>
        <p className="mono-sm" style={{ color: 'var(--fg-1)', lineHeight: 1.6, margin: 0 }}>{c.pgpNote}</p>
      </div>
    </aside>
  );
}

// Spinner helper
const spinnerCss = `
@keyframes spin { to { transform: rotate(360deg); } }
.spinner {
  width: 12px; height: 12px;
  border: 1.5px solid currentColor;
  border-top-color: transparent;
  border-radius: 50%;
  display: inline-block;
  animation: spin 720ms linear infinite;
}
`;
// Inject once
if (!document.getElementById('spinner-style')) {
  const style = document.createElement('style');
  style.id = 'spinner-style';
  style.textContent = spinnerCss;
  document.head.appendChild(style);
}

Object.assign(window, { AboutPage, CertificationsPage, ContactPage, ContactForm });
