/* APEX CLIPS — Submit Your Clip + License Footage + Contact (Supabase-wired) */

/* ---- form helpers ---- */
function Field({ label, req, children, full, hint }) {
  // Tie the label to its control so clicking the label focuses it and screen
  // readers announce the pairing. We inject a generated id onto the child input
  // (TextInput/Area/Select spread props straight to the DOM node); group
  // controls like YesNo/Chips harmlessly ignore it.
  const id = React.useId();
  const control = React.isValidElement(children)
    ? React.cloneElement(children, { id: children.props.id || id })
    : children;
  return (
    <div className={"field" + (full ? " field--full" : "")}>
      <label htmlFor={id}>{label}{req && <span className="req"> *</span>}</label>
      {control}
      {hint && <span className="field-hint">{hint}</span>}
    </div>
  );
}
function TextInput(props) { return <input className="input" {...props} />; }
function Area(props) { return <textarea className="textarea" {...props} />; }
function Select({ options, ...p }) {
  return <select className="select" {...p}>{options.map((o) => <option key={o} value={o === "Select…" ? "" : o}>{o}</option>)}</select>;
}
function YesNo({ value, onChange }) {
  return (
    <div className="seg" role="group">
      {["Yes", "No", "Unsure"].map((o) => (
        <button type="button" key={o} data-on={value === o} onClick={() => onChange(o)}>{o}</button>
      ))}
    </div>
  );
}
function Chips({ options, value, onToggle }) {
  return (
    <div className="chip-pick">
      {options.map((o) => (
        <button type="button" key={o} className="chip" data-on={value.includes(o)} onClick={() => onToggle(o)}>
          <span className="chip-box">{value.includes(o) ? "✓" : "＋"}</span>{o}
        </button>
      ))}
    </div>
  );
}

/* ================= SUBMIT ================= */
function Submit() {
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({
    name: "", email: "", country: "", social: "",
    clip_title: "", filmed_where: "", filmed_when: "", who_filmed: "", posted_online: "", story: "", source_url: "",
    owns_clip: "Yes", people_visible: "No", minors_visible: "No", music: "No", event_or_private: "No", agreed_terms: false,
  });
  const set = (k, v) => setForm((s) => ({ ...s, [k]: v }));
  const steps = ["About you", "The clip", "Rights & releases"];

  const send = async () => {
    setBusy(true);
    await submitLead("creator_submissions", {
      name: form.name, email: form.email, country: form.country, social_handle: form.social,
      clip_title: form.clip_title, filmed_where: form.filmed_where, filmed_when: form.filmed_when,
      who_filmed: form.who_filmed, posted_online: form.posted_online, story: form.story, source_url: form.source_url,
      owns_clip: form.owns_clip, people_visible: form.people_visible, minors_visible: form.minors_visible,
      music: form.music, event_or_private: form.event_or_private, agreed_terms: form.agreed_terms,
    });
    setBusy(false); setDone(true);
  };
  const next = () => { if (step < 2) { setStep(step + 1); window.scrollTo({ top: 0 }); } else send(); };
  const back = () => setStep(Math.max(0, step - 1));
  const reset = () => {
    setForm({ name: "", email: "", country: "", social: "", clip_title: "", filmed_where: "", filmed_when: "", who_filmed: "", posted_online: "", story: "", source_url: "", owns_clip: "Yes", people_visible: "No", minors_visible: "No", music: "No", event_or_private: "No", agreed_terms: false });
    setDone(false); setStep(0);
  };

  if (done) {
    return (
      <Page>
        <section className="section" style={{ minHeight: "70vh", display: "grid", placeItems: "center" }}>
          <div className="submit-done">
            <div className="submit-done-mark">✓</div>
            <Eyebrow>Submission received</Eyebrow>
            <h1 className="display" style={{ fontSize: "clamp(36px,5vw,60px)", marginTop: 14 }}>Your clip is in the queue.</h1>
            <p className="section-lead" style={{ margin: "14px auto 0" }}>Our verification team will review provenance, rights and releases, usually within 48 hours. You'll get an email at each stage, and you keep your copyright the whole way through.</p>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 28, flexWrap: "wrap" }}>
              <Link to="/creators" className="btn btn--accent btn--lg">How earnings work →</Link>
              <button className="btn btn--line btn--lg" onClick={reset}>Submit another clip</button>
            </div>
          </div>
        </section>
      </Page>
    );
  }

  return (
    <Page>
      <section className="form-hero">
        <Thumb cat="extreme" className="form-hero-bg" />
        <div className="form-hero-veil"></div>
        <div className="wrap" style={{ position: "relative", zIndex: 2 }}>
          <Eyebrow>Submit your clip</Eyebrow>
          <h1 className="display form-hero-h">Turn your best moments<br />into income.</h1>
          <p className="form-hero-sub">Upload from your phone in minutes. Keep your copyright. Earn every time your footage licenses, to media, brands and producers worldwide.</p>
          <div className="form-hero-trust">
            {["Keep ownership", "Fair revenue share", "Transparent reporting", "Rights protection"].map((t) => (
              <span key={t} className="mono form-hero-trust-i">✓ {t}</span>
            ))}
          </div>
        </div>
      </section>

      <section className="section--tight" style={{ paddingTop: 40, paddingBottom: 96 }}>
        <div className="wrap form-wrap">
          {/* progress */}
          <div className="wizard-steps">
            {steps.map((s, i) => (
              <div key={s} className="wizard-step" data-state={i === step ? "on" : i < step ? "done" : "off"}>
                <span className="wizard-dot">{i < step ? "✓" : i + 1}</span>
                <span className="wizard-label">{s}</span>
                {i < 2 && <span className="wizard-line"></span>}
              </div>
            ))}
          </div>

          <div className="card form-card">
            {step === 0 && (
              <div className="form-grid">
                <Field label="Full name" req><TextInput placeholder="Jordan Rivera" value={form.name} onChange={(e) => set("name", e.target.value)} /></Field>
                <Field label="Email" req><TextInput type="email" placeholder="you@email.com" value={form.email} onChange={(e) => set("email", e.target.value)} /></Field>
                <Field label="Country" req><Select options={["Select…", "Australia", "United Kingdom", "United States", "Indonesia", "Brazil", "Kenya", "Other"]} value={form.country} onChange={(e) => set("country", e.target.value)} /></Field>
                <Field label="Social handle" hint="So buyers can credit you"><TextInput placeholder="@yourhandle" value={form.social} onChange={(e) => set("social", e.target.value)} /></Field>
              </div>
            )}
            {step === 1 && (
              <div className="form-grid">
                <Field label="Clip title" req full><TextInput placeholder="e.g. Drone sweep over Nusa Penida cliffs" value={form.clip_title} onChange={(e) => set("clip_title", e.target.value)} /></Field>
                <Field label="Where was it filmed?" req><TextInput placeholder="City, country" value={form.filmed_where} onChange={(e) => set("filmed_where", e.target.value)} /></Field>
                <Field label="When was it filmed?" req><TextInput type="month" value={form.filmed_when} onChange={(e) => set("filmed_when", e.target.value)} /></Field>
                <Field label="Who filmed it?" req><Select options={["Select…", "I filmed it myself", "A friend filmed it", "It was on a shared device", "Other"]} value={form.who_filmed} onChange={(e) => set("who_filmed", e.target.value)} /></Field>
                <Field label="Has it been posted online?"><Select options={["Select…", "No, never", "Yes, on my socials", "Yes, it went viral"]} value={form.posted_online} onChange={(e) => set("posted_online", e.target.value)} /></Field>
                <Field label="What happened? Tell the story." req full><Area placeholder="Set the scene: what makes this moment unbelievable, and any context a newsroom or brand would need." value={form.story} onChange={(e) => set("story", e.target.value)} /></Field>
                <Field label="Source URL" hint="Link to the original post, if any" full><TextInput placeholder="https://" value={form.source_url} onChange={(e) => set("source_url", e.target.value)} /></Field>
                <Field label="Upload file" req full>
                  <div className="dropzone">
                    <div className="dropzone-ic">⤓</div>
                    <div><strong>Tap to upload</strong> or drag your clip here</div>
                    <div className="mono dropzone-note">MP4 / MOV · up to 4K · max 2GB · original quality preferred</div>
                  </div>
                </Field>
              </div>
            )}
            {step === 2 && <SubmitRights form={form} set={set} />}

            <div className="form-nav">
              {step > 0 ? <button className="btn btn--line" onClick={back} disabled={busy}>← Back</button> : <span />}
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <span className="mono form-nav-step">Step {step + 1} of 3</span>
                <button className="btn btn--accent" onClick={next} disabled={busy}>{step === 2 ? (busy ? "Submitting…" : "Submit clip →") : "Continue →"}</button>
              </div>
            </div>
          </div>

          <p className="mono form-foot-note">🔒 Your clip and details are confidential. We never list or pitch footage until verification and your contributor agreement are complete.</p>
        </div>
      </section>
    </Page>
  );
}

function SubmitRights({ form, set }) {
  return (
    <div className="form-grid">
      <Field label="Do you own this clip?" req><YesNo value={form.owns_clip} onChange={(v) => set("owns_clip", v)} /></Field>
      <Field label="Are people visible?"><YesNo value={form.people_visible} onChange={(v) => set("people_visible", v)} /></Field>
      <Field label="Are any minors visible?" req><YesNo value={form.minors_visible} onChange={(v) => set("minors_visible", v)} /></Field>
      <Field label="Is there music in the audio?"><YesNo value={form.music} onChange={(v) => set("music", v)} /></Field>
      <Field label="Filmed at an event / private property?" full><YesNo value={form.event_or_private} onChange={(v) => set("event_or_private", v)} /></Field>
      {(form.people_visible === "Yes" || form.event_or_private === "Yes") && (
        <div className="form-flag field--full">
          <span className="form-flag-ic">!</span>
          <span>No problem, our team will guide you through any talent or property releases needed. It won't slow down your submission.</span>
        </div>
      )}
      <div className="field--full" style={{ marginTop: 4 }}>
        <label className="chk">
          <input type="checkbox" checked={form.agreed_terms} onChange={(e) => set("agreed_terms", e.target.checked)} />
          <span>I confirm the information is accurate and I agree to the <span style={{ color: "var(--accent)", fontWeight: 600 }}>Contributor Terms</span>. I keep my copyright; Apex Clips licenses on my behalf for an agreed revenue share.</span>
        </label>
      </div>
    </div>
  );
}

/* ================= LICENSE ================= */
function License() {
  const [f, setF] = useState({ name: "", company: "", role: "", email: "", usage: "", platforms: [], territory: "", term: "", monet: "No", paid: "No", commercial: "No", clips: "1–5", deadline: "", brief: "" });
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const toggle = (k, v) => setF((s) => ({ ...s, [k]: s[k].includes(v) ? s[k].filter((x) => x !== v) : [...s[k], v] }));

  const send = async () => {
    setBusy(true);
    await submitLead("buyer_leads", {
      lead_type: "license", name: f.name, company: f.company, role: f.role, email: f.email,
      usage_type: f.usage, platforms: f.platforms.join(", "), territory: f.territory, term: f.term, clips: f.clips,
      monetization: f.monet, paid_media: f.paid, commercial: f.commercial, deadline: f.deadline, brief: f.brief,
    });
    setBusy(false); setSent(true); window.scrollTo({ top: 0 });
  };

  if (sent) {
    return (
      <Page>
        <section className="section" style={{ minHeight: "70vh", display: "grid", placeItems: "center" }}>
          <div className="submit-done">
            <div className="submit-done-mark">✓</div>
            <Eyebrow>Brief received</Eyebrow>
            <h1 className="display" style={{ fontSize: "clamp(36px,5vw,60px)", marginTop: 14 }}>Our content desk is on it.</h1>
            <p className="section-lead" style={{ margin: "14px auto 0" }}>You'll get matched, rights-cleared options and a quote, typically within one business day. Need it faster? Reply to our email and we'll prioritise.</p>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 28, flexWrap: "wrap" }}>
              <Link to="/library" className="btn btn--accent btn--lg">Browse the library →</Link>
              <button className="btn btn--line btn--lg" onClick={() => setSent(false)}>Send another brief</button>
            </div>
          </div>
        </section>
      </Page>
    );
  }

  return (
    <Page>
      <section className="form-hero">
        <Thumb cat="travel" className="form-hero-bg" />
        <div className="form-hero-veil"></div>
        <div className="wrap" style={{ position: "relative", zIndex: 2 }}>
          <Eyebrow>License footage</Eyebrow>
          <h1 className="display form-hero-h">Rights-cleared adventure<br />footage, ready to publish.</h1>
          <p className="form-hero-sub">Request access and tell us what you need and how you'll use it. Our team opens the library and returns verified, cleared options and a quote, built for social teams, producers and rights managers.</p>
          <div className="form-hero-trust">
            {["Cleared for agreed usage", "Fast preview & quoting", "Editorial context included", "Bulk & rev-share"].map((t) => (
              <span key={t} className="mono form-hero-trust-i">✓ {t}</span>
            ))}
          </div>
        </div>
      </section>

      <section className="section--tight" style={{ paddingTop: 40, paddingBottom: 96 }}>
        <div className="wrap license-layout">
          <div className="card form-card">
            <h3 className="form-section-h">Your details</h3>
            <div className="form-grid">
              <Field label="Name" req><TextInput placeholder="Jordan Rivera" value={f.name} onChange={(e) => set("name", e.target.value)} /></Field>
              <Field label="Company" req><TextInput placeholder="Studio / publisher / brand" value={f.company} onChange={(e) => set("company", e.target.value)} /></Field>
              <Field label="Role"><Select options={["Select…", "Social / content lead", "Producer", "Editor", "Rights / legal", "Brand manager", "Agency"]} value={f.role} onChange={(e) => set("role", e.target.value)} /></Field>
              <Field label="Work email" req><TextInput type="email" placeholder="you@company.com" value={f.email} onChange={(e) => set("email", e.target.value)} /></Field>
            </div>

            <h3 className="form-section-h" style={{ marginTop: 32 }}>Your usage</h3>
            <div className="form-grid">
              <Field label="Usage type" req><Select options={["Select…", ...USAGE_TYPES]} value={f.usage} onChange={(e) => set("usage", e.target.value)} /></Field>
              <Field label="Territory" req><Select options={["Select…", "Worldwide", "Single country", "Region (e.g. EMEA)", "Online only"]} value={f.territory} onChange={(e) => set("territory", e.target.value)} /></Field>
              <Field label="Platforms" req full>
                <Chips options={PLATFORMS} value={f.platforms} onToggle={(v) => toggle("platforms", v)} />
              </Field>
              <Field label="Licence term" req><Select options={["Select…", "Single use", "3 months", "12 months", "Perpetual", "Buyout"]} value={f.term} onChange={(e) => set("term", e.target.value)} /></Field>
              <Field label="Number of clips needed"><Select options={["1–5", "6–20", "20–50", "50+ / ongoing"]} value={f.clips} onChange={(e) => set("clips", e.target.value)} /></Field>
              <Field label="Monetization required?"><YesNo value={f.monet} onChange={(v) => set("monet", v)} /></Field>
              <Field label="Paid media required?"><YesNo value={f.paid} onChange={(v) => set("paid", v)} /></Field>
              <Field label="Commercial use?"><YesNo value={f.commercial} onChange={(v) => set("commercial", v)} /></Field>
              <Field label="Deadline"><TextInput type="date" value={f.deadline} onChange={(e) => set("deadline", e.target.value)} /></Field>
              <Field label="Brief: what are you looking for?" req full>
                <Area placeholder="e.g. 6–8 vertical surf & drone clips from SE Asia, cleared for paid social, EMEA, 12 months. Hero campaign launching next month." style={{ minHeight: 130 }} value={f.brief} onChange={(e) => set("brief", e.target.value)} />
              </Field>
            </div>
          </div>

          {/* live summary */}
          <aside className="license-summary">
            <div className="card license-summary-card">
              <span className="mono" style={{ fontSize: 11, letterSpacing: ".14em", color: "var(--ink-4)" }}>ENQUIRY SUMMARY</span>
              <h3 className="display" style={{ fontSize: 26, marginTop: 10 }}>Your licence shape</h3>
              <div className="summary-rows">
                <SumRow k="Usage" v={f.usage || "Not set"} />
                <SumRow k="Platforms" v={f.platforms.length ? f.platforms.join(", ") : "Not set"} />
                <SumRow k="Territory" v={f.territory || "Not set"} />
                <SumRow k="Term" v={f.term || "Not set"} />
                <SumRow k="Volume" v={f.clips} />
                <SumRow k="Monetization" v={f.monet} />
                <SumRow k="Paid media" v={f.paid} />
                <SumRow k="Commercial" v={f.commercial} />
              </div>
              <button className="btn btn--accent btn--lg btn--block" style={{ marginTop: 18 }} onClick={send} disabled={busy}>{busy ? "Sending…" : "Send Brief →"}</button>
              <p className="mono detail-buy-note" style={{ textAlign: "center" }}>No commitment. We reply with cleared options &amp; a quote within 1 business day.</p>
            </div>
            <div className="card license-help">
              <strong>Prefer to talk?</strong>
              <p style={{ color: "var(--ink-3)", margin: "6px 0 12px", fontSize: 14 }}>Rights or legal questions before you brief?</p>
              <Link to="/rights" className="arrow-link">See rights &amp; verification →</Link>
            </div>
          </aside>
        </div>
      </section>
    </Page>
  );
}
function SumRow({ k, v }) {
  return (
    <div className="summary-row">
      <span className="mono summary-k">{k}</span>
      <span className="summary-v">{v}</span>
    </div>
  );
}

/* ================= CONTACT ================= */
function Contact() {
  const [f, setF] = useState({ name: "", email: "", iam: "", company: "", message: "" });
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const cards = [
    ["Licensing & briefs", "Source, quote and clear footage for your project.", "License Footage", "/license"],
    ["Become a creator", "Submit footage and start earning from your clips.", "Submit Your Clip", "/submit"],
    ["Rights & legal", "Questions on clearance, releases or liability.", "Rights & Verification", "/rights"],
  ];
  const send = async () => {
    setBusy(true);
    await submitLead("buyer_leads", { lead_type: "contact", name: f.name, email: f.email, role: f.iam, company: f.company, brief: f.message });
    setBusy(false); setSent(true); window.scrollTo({ top: 0 });
  };

  return (
    <Page>
      <section className="section--tight" style={{ paddingTop: 64 }}>
        <div className="wrap">
          <Eyebrow>Contact</Eyebrow>
          <h1 className="display" style={{ fontSize: "clamp(40px,6vw,82px)", marginTop: 14 }}>Talk to the desk.</h1>
          <p className="section-lead" style={{ maxWidth: 560 }}>Whether you're sourcing footage, submitting a clip, or your legal team has questions, we're quick to respond.</p>
        </div>
      </section>
      <section className="section--tight" style={{ paddingTop: 8, paddingBottom: 96 }}>
        <div className="wrap contact-layout">
          <div className="card form-card">
            {sent ? (
              <div style={{ textAlign: "center", padding: "40px 0" }}>
                <div className="submit-done-mark" style={{ margin: "0 auto 18px" }}>✓</div>
                <h3 className="display" style={{ fontSize: 32 }}>Message sent.</h3>
                <p style={{ color: "var(--ink-3)", marginTop: 8 }}>We'll be in touch within one business day.</p>
                <button className="btn btn--line" style={{ marginTop: 20 }} onClick={() => setSent(false)}>Send another</button>
              </div>
            ) : (
              <React.Fragment>
                <h3 className="form-section-h">Send us a message</h3>
                <div className="form-grid">
                  <Field label="Name" req><TextInput placeholder="Your name" value={f.name} onChange={(e) => set("name", e.target.value)} /></Field>
                  <Field label="Email" req><TextInput type="email" placeholder="you@email.com" value={f.email} onChange={(e) => set("email", e.target.value)} /></Field>
                  <Field label="I am a…"><Select options={["Select…", "Publisher / media", "Brand / agency", "Producer / filmmaker", "Creator", "Press", "Other"]} value={f.iam} onChange={(e) => set("iam", e.target.value)} /></Field>
                  <Field label="Company"><TextInput placeholder="Optional" value={f.company} onChange={(e) => set("company", e.target.value)} /></Field>
                  <Field label="How can we help?" req full><Area placeholder="Tell us what you need." value={f.message} onChange={(e) => set("message", e.target.value)} /></Field>
                </div>
                <button className="btn btn--accent btn--lg" style={{ marginTop: 22 }} onClick={send} disabled={busy}>{busy ? "Sending…" : "Send Message →"}</button>
              </React.Fragment>
            )}
          </div>
          <aside style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {cards.map(([t, b, cta, to]) => (
              <Link key={t} to={to} className="card contact-card">
                <h4 className="contact-card-h">{t}</h4>
                <p className="contact-card-b">{b}</p>
                <span className="arrow-link">{cta} →</span>
              </Link>
            ))}
            <div className="card contact-card" style={{ background: "var(--bg-2)" }}>
              <h4 className="contact-card-h">Content desk</h4>
              <p className="mono" style={{ color: "var(--ink-2)", fontSize: 14, margin: "6px 0 2px" }}>desk@apexclips.com</p>
              <p className="mono" style={{ color: "var(--ink-2)", fontSize: 14 }}>creators@apexclips.com</p>
              <p className="mono" style={{ color: "var(--ink-4)", fontSize: 12, marginTop: 10 }}>LONDON · SYDNEY · LOS ANGELES</p>
            </div>
          </aside>
        </div>
      </section>
    </Page>
  );
}

Object.assign(window, { Submit, License, Contact, Field, TextInput, Area, Select, YesNo, Chips });
