/* global React */
const { useState: useStateOv, useEffect: useEffectOv } = React;

/* ============================================================
   MAIN MENU OVERLAY
   ============================================================ */
function MainMenu({ onClose, onContact, onNav }) {
  useEffectOv(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div className="h-overlay">
      <div className="ov-logo">
        <div className="lname">NICKO TRENCHEV</div>
        <div className="lsub">STUDIO</div>
      </div>
      <button className="ov-close" onClick={onClose}>CLOSE</button>

      <div className="mm-items" style={{ display: "contents" }}>
        <div className="mm-contact">
          <a className="mm-item big" style={{ animationDelay: "0.06s" }} onClick={onContact}>CONTACT</a>
          <div className="mm-socials">
            <a className="mm-item" style={{ animationDelay: "0.12s" }} href="#">INSTAGRAM</a>
            <a className="mm-item" style={{ animationDelay: "0.17s" }} href="#">PINTEREST</a>
            <a className="mm-item" style={{ animationDelay: "0.22s" }} href="#">FACEBOOK</a>
          </div>
        </div>

        <div className="mm-primary">
          <a className="mm-item" style={{ animationDelay: "0.14s" }} onClick={() => onNav("portfolio")}>PORTFOLIO</a>
          <a className="mm-item" style={{ animationDelay: "0.20s" }} onClick={() => onNav("about")}>ABOUT US</a>
        </div>

        <div className="mm-secondary">
          <a className="mm-item" style={{ animationDelay: "0.30s" }} href="#">PHOTOBOOK/MAGAZINE</a>
          <a className="mm-item" style={{ animationDelay: "0.36s" }} href="#">SEARCH</a>
          <a className="mm-item" style={{ animationDelay: "0.42s" }} href="#">FAQ</a>
        </div>

        <div className="mm-foot">
          <a className="mm-item" style={{ animationDelay: "0.50s" }} href="#">PRIVACY POLICY</a>
          <a className="mm-item" style={{ animationDelay: "0.54s" }} href="#">COMMERCIAL COPYRIGHT</a>
          <a className="mm-item" style={{ animationDelay: "0.58s" }} href="#">CREATIVITY PROJECT</a>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   GALLERY-TYPE MENU (over dimmed grid) — opened by "+"
   Shared by the home page AND the galleries page so both show the
   exact same list. The categories come from /api/galleries, which is
   editable in the admin panel (Galleries → add / remove / reorder).
   ============================================================ */
function galleryMenuLabel(g) {
  // Keep the menu label short for the long "Weddings & Editorials" label.
  return g.key === "weddings" ? "WEDDINGS" : (g.label || g.key).toUpperCase();
}

function TypesMenu({ galleries, activeKey, onPick }) {
  return (
    <div className="h-types">
      <div className="types-list">
        {(galleries || []).map((g, i) => (
          <button
            key={g.key}
            className="ty"
            style={{ animationDelay: `${0.05 + i * 0.045}s`, color: g.key === activeKey ? "#fff" : undefined }}
            onClick={() => onPick(g.key)}
          >{galleryMenuLabel(g)}</button>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   CONTACT FORM OVERLAY
   ============================================================ */
const EVENT_TYPES = ["Wedding", "Editorial", "Event", "Baptism", "Portrait", "Other"];
const ROLES = ["Bride", "Groom", "Planner", "Family", "Brand", "Other"];
const COVERAGE = ["Half day", "Full day", "Multi-day", "Destination", "Not sure yet"];
const GUESTS = ["Under 50", "50–100", "100–200", "200–350", "350+"];

function ContactForm({ onClose }) {
  const [f, setF] = useStateOv({
    name: "", email: "", live: "", eventType: "", role: "",
    date: "", location: "", guests: "", coverage: "", instagram: "", message: "",
  });
  const [sent, setSent] = useStateOv(false);
  const [sending, setSending] = useStateOv(false);
  const [error, setError] = useStateOv("");
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));

  useEffectOv(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const submit = async (e) => {
    e.preventDefault();
    if (!f.name || !f.email || sending) return;
    setSending(true); setError("");
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: f.name, email: f.email, location: f.live, eventType: f.eventType,
          role: f.role, date: f.date, event_location: f.location, guests: f.guests,
          coverage: f.coverage, instagram: f.instagram, message: f.message,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "Something went wrong. Please try again.");
      setSent(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setSending(false);
    }
  };

  const Sel = ({ k, label, opts }) => (
    <div className="cf-field">
      <select className={f[k] ? "filled" : ""} value={f[k]} onChange={(e) => set(k, e.target.value)}>
        <option value="">{label}</option>
        {opts.map((o) => <option key={o} value={o} style={{ color: "#1a1a1a" }}>{o.toUpperCase()}</option>)}
      </select>
      <span className="chev">▾</span>
    </div>
  );

  return (
    <div className="h-contact">
      <div className="cf-head">
        <div className="lname">NICKO TRENCHEV</div>
        <div className="lsub">STUDIO</div>
      </div>
      <button className="cf-close" onClick={onClose}>CLOSE</button>

      <div className="cf-inner">
        {sent ? (
          <div className="cf-sent">
            <h2>Thank you, {f.name.split(" ")[0] || "friend"}.</h2>
            <p>Your enquiry is in. We read every message ourselves and reply within two working days — usually with a few dates and a deck.</p>
            <button className="cf-send" style={{ margin: "40px auto 0" }} onClick={onClose}>
              CLOSE
            </button>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div className="cf-grid">
              <div className="cf-field">
                <input placeholder="FULL NAME" value={f.name} onChange={(e) => set("name", e.target.value)} />
              </div>
              <div className="cf-field">
                <input type="email" placeholder="EMAIL" value={f.email} onChange={(e) => set("email", e.target.value)} />
              </div>

              <div className="cf-field">
                <input placeholder="WHERE DO YOU LIVE?" value={f.live} onChange={(e) => set("live", e.target.value)} />
              </div>
              <Sel k="eventType" label="EVENT TYPE" opts={EVENT_TYPES} />

              <Sel k="role" label="WHAT IS YOUR ROLE?" opts={ROLES} />
              <div className="cf-field">
                <input placeholder="DATE" value={f.date} onChange={(e) => set("date", e.target.value)} onFocus={(e)=>e.target.type="date"} onBlur={(e)=>{ if(!e.target.value) e.target.type="text"; }} />
              </div>

              <div className="cf-field">
                <input placeholder="EVENT LOCATION" value={f.location} onChange={(e) => set("location", e.target.value)} />
              </div>
              <Sel k="guests" label="GUEST COUNT" opts={GUESTS} />

              <Sel k="coverage" label="PHOTOGRAPHY COVERAGE" opts={COVERAGE} />
              <div className="cf-field">
                <input placeholder="INSTAGRAM" value={f.instagram} onChange={(e) => set("instagram", e.target.value)} />
              </div>

              <div className="cf-field full">
                <textarea placeholder="MESSAGE" value={f.message} onChange={(e) => set("message", e.target.value)} />
              </div>
            </div>

            <div className="cf-bottom">
              <div className="cf-consent">
                <input type="checkbox" id="cf-consent" required />
                <label htmlFor="cf-consent">I consent for the information submitted above to be recorded and stored for the purposes of providing services relating to my enquiry. I agree that use of this site constitutes agreement to its user agreement &amp; privacy policy.</label>
              </div>
              <button className="cf-send" type="submit" disabled={sending} style={sending ? { opacity: 0.6 } : undefined}>
                {sending ? "SENDING…" : "SEND"}
                <svg viewBox="0 0 80 26" fill="none"><path d="M0 13h74M64 4l11 9-11 9" stroke="#1a1a1a" strokeWidth="3"/></svg>
              </button>
            </div>
            {error && <div style={{ marginTop: 16, color: "#b00", fontSize: 13, letterSpacing: ".04em" }}>{error}</div>}
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MainMenu, TypesMenu, ContactForm, galleryMenuLabel });
