/* Atmosphere — demo request form (React island, no external libs, no storage).
   Submits to the Supabase `leads` table via PostgREST. The key below is a
   Supabase *publishable* (anon) key — safe to ship client-side; inserts are
   gated by RLS (policy `leads_anon_insert`, anon INSERT only). */
const { useState } = React;

const SUPABASE_URL = "https://zuwmqxsrrythmqyvzerf.supabase.co";
const SUPABASE_ANON_KEY = "sb_publishable_EqZcloPJppKfluVVGJ_VQA_8mUoAnLG";
const LEADS_ENDPOINT = SUPABASE_URL + "/rest/v1/leads";

const VENUE_TYPES = ["Café", "Restaurant", "Hotel", "Bar/Lounge", "Retail", "Other"];

function Field({ label, opt, children }) {
  return (
    <div className="field">
      <label>{label}{opt ? <span className="opt"> (optional)</span> : null}</label>
      {children}
    </div>
  );
}

function DemoForm() {
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [f, setF] = useState({
    name: "", venue: "", email: "", phone: "", type: "", message: ""
  });
  const set = (k) => (e) => setF((p) => ({ ...p, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError("");
    setSending(true);
    try {
      const res = await fetch(LEADS_ENDPOINT, {
        method: "POST",
        headers: {
          "apikey": SUPABASE_ANON_KEY,
          "Authorization": "Bearer " + SUPABASE_ANON_KEY,
          "Content-Type": "application/json",
          "Prefer": "return=minimal"
        },
        body: JSON.stringify({
          contact_name: f.name.trim(),
          business_name: f.venue.trim(),
          email: f.email.trim(),
          phone: f.phone.trim() || null,
          venue_type: f.type || null,
          message: f.message.trim() || null,
          source: "landing"
        })
      });
      if (!res.ok) {
        const detail = await res.text().catch(() => "");
        throw new Error("HTTP " + res.status + (detail ? " — " + detail : ""));
      }
      setSent(true);
    } catch (err) {
      console.error("Lead submit failed:", err);
      setError("Something went wrong sending your request. Please try again, or email us at hello@tabbled.com.");
    } finally {
      setSending(false);
    }
  };

  if (sent) {
    return (
      <div className="form-success" role="status">
        <div className="chk">
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor"
            strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M20 6 9 17l-5-5" />
          </svg>
        </div>
        <h3>Thank you — your demo's on the way.</h3>
        <p>We'll be in touch shortly to set the atmosphere for your venue.</p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} noValidate>
      <div className="field-row">
        <Field label="Your name">
          <input type="text" value={f.name} onChange={set("name")} placeholder="Jane Doe" required />
        </Field>
        <Field label="Venue name">
          <input type="text" value={f.venue} onChange={set("venue")} placeholder="Café Marmara" required />
        </Field>
      </div>
      <div className="field-row">
        <Field label="Email">
          <input type="email" value={f.email} onChange={set("email")} placeholder="jane@cafemarmara.com" required />
        </Field>
        <Field label="Phone" opt>
          <input type="tel" value={f.phone} onChange={set("phone")} placeholder="+90 5xx xxx xx xx" />
        </Field>
      </div>
      <Field label="Venue type">
        <select value={f.type} onChange={set("type")} required>
          <option value="" disabled>Select venue type</option>
          {VENUE_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
        </select>
      </Field>
      <Field label="Message" opt>
        <textarea value={f.message} onChange={set("message")} placeholder="Tell us about your space, your hours, the mood you're after…" />
      </Field>
      {error ? <p className="form-error" role="alert">{error}</p> : null}
      <button type="submit" className="btn btn-primary" disabled={sending}>
        {sending ? "Sending…" : "Request a demo"}
      </button>
      <p className="form-note">We'll only use this to arrange your demo.</p>
    </form>
  );
}

ReactDOM.createRoot(document.getElementById("demo-root")).render(<DemoForm />);
