/* ============================================================
   COMMONS — Host an event flow (form + live preview)
   ============================================================ */

function HostField({ label, hint, children }) {
  return (
    <div className="hfield">
      <div className="hfield-l"><b>{label}</b>{hint && <span>{hint}</span>}</div>
      {children}
    </div>
  );
}

function isoToNice(iso) {
  try {
    const d = new Date(iso + "T00:00:00");
    if (isNaN(d)) return "Sat, Jun 21";
    const wd = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][d.getDay()];
    const mo = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][d.getMonth()];
    return wd + ", " + mo + " " + String(d.getDate()).padStart(2, "0");
  } catch (e) { return "Sat, Jun 21"; }
}

function HostEvent({ go }) {
  const [f, setF] = useState({
    title: "", cat: "Community", date: "", time: "6:00 PM",
    venue: "", city: "", free: true, price: "", cap: 40, desc: "",
  });
  const [seed, setSeed] = useState("new-event-1");
  const [published, setPublished] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const cats = ["Music", "Festival", "Kirtan", "Food", "Sports", "Community", "Film"];

  const publish = async () => {
    if (!f.title || !f.venue || !f.date) return;
    if (!(typeof window !== "undefined" && window.__USER__)) { setErr("Please log in to publish."); return; }
    setBusy(true); setErr("");
    try {
      const r = await fetch("/api/events", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title: f.title, date: f.date, time: f.time, venue: f.venue, city: f.city, description: f.desc, ticket_url: f.free ? "" : "tickets" }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) { setErr(j.error || "Could not publish event."); setBusy(false); return; }
      setPublished(true);
    } catch (e) { setErr("Network error — please try again."); setBusy(false); }
  };

  const preview = {
    id: seed,
    title: f.title || "Your event title",
    cat: f.cat,
    date: isoToNice(f.date),
    time: f.time,
    venue: f.venue || "Your venue",
    dist: f.city || "Worldwide",
    price: f.free ? "Free" : (f.price ? "$" + f.price : "$—"),
    going: 1, host: "You", hostU: "you",
  };

  if (published) {
    return (
      <div className="view host-done">
        <div className="shell host-done-inner">
          <div className="host-done-card surface">
            <span className="host-check"><Icon name="check" size={34} /></span>
            <span className="kicker">You're live</span>
            <h1 className="serif">{preview.title}</h1>
            <p>Your event is published and discoverable to Punjabis worldwide. We'll email you when the first person RSVPs.</p>
            <div className="host-done-actions">
              <button className="btn btn-primary" onClick={() => { location.hash = "/discover"; location.reload(); }}><Icon name="compass" size={16} /> See it on Discover</button>
              <button className="btn btn-ghost" onClick={() => { setPublished(false); }}>Edit details</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="view host">
      <div className="shell">
        <button className="back" onClick={() => go("discover")}><Icon name="arrowLeft" size={16} /> Cancel</button>
        <div className="host-head">
          <span className="kicker">Host on iPanjab</span>
          <h1 className="serif">Throw something worth showing up for.</h1>
        </div>

        <div className="host-grid">
          <form className="host-form" onSubmit={e => e.preventDefault()}>
            <HostField label="What's the event?">
              <input className="host-title-input" placeholder="Give it a name people will remember…" value={f.title} onChange={e => set("title", e.target.value)} />
            </HostField>

            <HostField label="Category">
              <div className="host-chips">
                {cats.map(c => <button key={c} type="button" className="chip" data-on={f.cat === c} onClick={() => set("cat", c)}>{c}</button>)}
              </div>
            </HostField>

            <div className="host-row">
              <HostField label="Date">
                <div className="input-icon"><Icon name="calendar" size={16} /><input type="date" value={f.date} onChange={e => set("date", e.target.value)} /></div>
              </HostField>
              <HostField label="Start time">
                <div className="input-icon"><Icon name="clock" size={16} /><input value={f.time} onChange={e => set("time", e.target.value)} /></div>
              </HostField>
            </div>

            <HostField label="Where" hint="Venue and city.">
              <div className="input-icon"><Icon name="pin" size={16} /><input placeholder="Venue, e.g. Gurdwara Sahib Dixie" value={f.venue} onChange={e => set("venue", e.target.value)} /></div>
              <div className="input-icon" style={{ marginTop: 8 }}><Icon name="pin" size={16} /><input placeholder="City, e.g. Brampton" value={f.city} onChange={e => set("city", e.target.value)} /></div>
            </HostField>

            <HostField label="Description" hint="What should people expect?">
              <textarea rows={4} placeholder="Set the vibe. What happens, who it's for, what to bring…" value={f.desc} onChange={e => set("desc", e.target.value)} />
            </HostField>

            <div className="host-row">
              <HostField label="Price">
                <div className="host-price">
                  <button type="button" className="seg" data-on={f.free} onClick={() => set("free", true)}>Free</button>
                  <button type="button" className="seg" data-on={!f.free} onClick={() => set("free", false)}>Paid</button>
                  {!f.free && <div className="input-icon price-in"><Icon name="dollar" size={16} /><input type="number" placeholder="15" value={f.price} onChange={e => set("price", e.target.value)} /></div>}
                </div>
              </HostField>
              <HostField label="Capacity">
                <div className="input-icon"><Icon name="users" size={16} /><input type="number" value={f.cap} onChange={e => set("cap", e.target.value)} /></div>
              </HostField>
            </div>

            <HostField label="Cover" hint="Pick a look — we'll generate it.">
              <div className="host-covers">
                {["new-event-1", "vol9", "studio", "yard", "ridge", "rooftop"].map(s => (
                  <button key={s} type="button" className="host-cover-opt" data-on={seed === s} onClick={() => setSeed(s)}>
                    <Cover seed={s} aspect="16 / 10" radius="8px" />
                  </button>
                ))}
              </div>
            </HostField>
          </form>

          <aside className="host-preview">
            <div className="host-preview-sticky">
              <span className="kicker">Live preview</span>
              <article className="ev-card host-pv-card">
                <Cover seed={seed} aspect="16 / 11" radius="12px" className="ev-cover">
                  <div className="ev-cover-top">
                    <span className="ev-date-chip">
                      <b>{(preview.date.split(", ")[1] || "Jun 21").split(" ")[1]}</b>
                      <span>{(preview.date.split(", ")[1] || "Jun 21").split(" ")[0]}</span>
                    </span>
                  </div>
                  <div className="ev-cover-cat">{preview.cat}</div>
                </Cover>
                <div className="ev-body">
                  <h3 className="ev-title serif">{preview.title}</h3>
                  <div className="ev-meta">
                    <span><Icon name="clock" size={14} />{preview.time}</span>
                    <span><Icon name="pin" size={14} />{preview.venue.split(",")[0]}</span>
                  </div>
                  <div className="ev-foot">
                    <div className="ev-host"><Avatar seed="you" label="You" size={22} /><span>You</span></div>
                    <span className="ev-price" data-free={preview.price === "Free"}>{preview.price}</span>
                  </div>
                </div>
              </article>
              <button className="btn btn-primary host-publish" onClick={publish} disabled={busy || !f.title || !f.venue || !f.date}>
                <Icon name="bolt" size={17} /> {busy ? "Publishing…" : "Publish event"}
              </button>
              {err && <p className="host-pv-note" style={{ color: "var(--accent)" }}>{err}</p>}
              <p className="host-pv-note">{(!f.title || !f.venue || !f.date) ? "Add a title, venue and date to publish." : "Looks great — you're ready to go."}</p>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

window.HostEvent = HostEvent;
