// ============================================================
// Contact page + inquiry form - FreshWave Digital Studio
// ============================================================

function InquiryForm() {
  const [form, setForm] = useState({ name: '', email: '', project: '', type: '', budget: '', message: '' });
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const [fallbackMailto, setFallbackMailto] = useState('');
  const [ticket, setTicket] = useState('');
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.message) return;
    setSending(true);
    setFallbackMailto('');
    setTicket('');

    const payload = {
      kind: 'contact',
      name: form.name,
      email: form.email,
      project: form.project,
      category: form.type,
      budget: form.budget,
      message: form.message,
    };

    try {
      const result = await submitInquiry(payload);
      setTicket(result.ticket || '');
      setSent(true);
    } catch (error) {
      const mailto = buildInquiryMailto(payload);
      setFallbackMailto(mailto);
      window.location.href = mailto;
      setSent(true);
    } finally {
      setSending(false);
    }
  };

  if (sent) {
    return (
      <div className="reading-surface rounded-2xl border border-border bg-card p-10 text-center">
        <span className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-full bg-primary glow-cyan">
          <Icon name="check" className="h-8 w-8" stroke={3} style={{ color: 'hsl(var(--primary-foreground))' }} />
        </span>
        <h3 className="crt-head mb-2 font-heading text-2xl">Message received</h3>
        <p className="mb-6 text-muted-foreground">We'll get back to you within 72 hours. Often sooner when the queue is light.</p>
        {ticket && <p className="mb-6 font-mono text-xs uppercase tracking-[0.25em] text-primary">Ticket {ticket}</p>}
        {fallbackMailto && (
          <div className="mb-6 rounded-xl border border-border bg-background/50 p-4 text-sm text-muted-foreground">
            The server form was unavailable, so we opened a backup email draft with your details. If it did not open, use the button below.
            <a href={fallbackMailto} className="mt-3 inline-flex font-heading text-xs uppercase tracking-wider text-primary hover:underline">Open email draft</a>
          </div>
        )}
        <Button variant="outline" onClick={() => { setSent(false); setFallbackMailto(''); setTicket(''); setForm({ name: '', email: '', project: '', type: '', budget: '', message: '' }); }}>Send another</Button>
      </div>
    );
  }

  const TYPES = ['Anime Figure', 'Vintage / Replica', 'Fidget Toy', 'Statue', 'Not sure'];
  const BUDGETS = ['Under $50', '$50-$100', '$100-$200', '$200+ (statues)'];

  return (
    <form onSubmit={submit} className="reading-surface space-y-6 rounded-2xl border border-border bg-card p-6 md:p-8">
      <div className="grid gap-6 md:grid-cols-2">
        <Field label="Name *"><input value={form.name} onChange={(e) => set('name', e.target.value)} required placeholder="Maya Chen" className="fw-input" /></Field>
        <Field label="Email *"><input type="email" value={form.email} onChange={(e) => set('email', e.target.value)} required placeholder="maya@example.com" className="fw-input" /></Field>
      </div>
      <Field label="Project name"><input value={form.project} onChange={(e) => set('project', e.target.value)} placeholder="Glowing trophy, replacement gear, …" className="fw-input" /></Field>

      <div className="grid gap-6 md:grid-cols-2">
        <Field label="Type of piece">
          <div className="flex flex-wrap gap-2">
            {TYPES.map((t) => (
              <Button key={t} type="button" size="sm" variant={form.type === t ? 'default' : 'outline'} onClick={() => set('type', t)}>{t}</Button>
            ))}
          </div>
        </Field>
        <Field label="Rough budget">
          <div className="flex flex-wrap gap-2">
            {BUDGETS.map((b) => (
              <Button key={b} type="button" size="sm" className="font-data text-sm tracking-[0.04em]" variant={form.budget === b ? 'default' : 'outline'} onClick={() => set('budget', b)}>{b}</Button>
            ))}
          </div>
        </Field>
      </div>

      <Field label="Message *">
        <textarea value={form.message} onChange={(e) => set('message', e.target.value)} required rows={6} placeholder="Tell us what you want to make…" className="fw-input resize-none"></textarea>
      </Field>

      <Button type="submit" disabled={sending} className="w-full md:w-auto">
        {sending ? (<><Icon name="spinner" /> Sending…</>) : (<>Send inquiry <Icon name="arrow-right" /></>)}
      </Button>
    </form>
  );
}

function ContactPage() {
  return (
    <div className="scanlines">
      <div className="container mx-auto py-16">
        <div className="mb-12 text-center">
          <Eyebrow accent="magenta"><span className="mx-auto">Say hello</span></Eyebrow>
          <h1 className="crt-head mb-4 font-heading text-4xl md:text-5xl lg:text-6xl" style={{ letterSpacing: '-0.02em' }}>Let's talk</h1>
          <p className="mx-auto max-w-2xl text-lg text-muted-foreground">
            Got a character to immortalize, a vintage piece to recreate, or just a half-formed idea? Drop us a line and we'll come back within 72 hours.
          </p>
        </div>

        <div className="mx-auto max-w-2xl">
          <InquiryForm />
        </div>

        <div className="mt-14 grid gap-6 sm:grid-cols-3">
          {[
            { k: 'Email', v: (window.FRESHWAVE_CONFIG || {}).contactEmail || 'customerservice@freshwavefinds.shop', href: `mailto:${(window.FRESHWAVE_CONFIG || {}).contactEmail || 'customerservice@freshwavefinds.shop'}` },
            { k: 'Studio', v: 'Bench 04, The Maker Block', href: null },
            { k: 'Turnaround', v: 'Within 72h', href: null },
          ].map((c) => (
            <div key={c.k} className="card-accent rounded-xl border border-border bg-card p-6 text-center">
              <div className="mb-2 font-mono text-[10px] uppercase tracking-[0.25em] text-[hsl(var(--cyan))] neon-text-soft">{c.k}</div>
              {c.href ? (
                <a href={c.href} className="text-sm text-primary transition-colors hover:underline">{c.v}</a>
              ) : (
                <div className="text-sm">{c.v}</div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ContactPage, InquiryForm });
