/* ============================================================
   iPanjab — New post composer (working)
   ============================================================ */

const POST_TAGS = ["Discussion", "Question", "Recommendation", "Trail report", "Giveaway", "Advice", "PSA"];

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

function NewPost({ go, addPost, presetSub }) {
  const [sub, setSub] = useState(presetSub || "");
  const [tag, setTag] = useState("Discussion");
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [img, setImg] = useState(false);
  const [seed] = useState("post-" + Math.random().toString(36).slice(2, 8));
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const ready = sub && title.trim().length > 3;

  const preview = {
    id: seed,
    sub: sub || "pick-a-community",
    author: "you",
    time: "now",
    title: title || "Your post title will appear here",
    body: body || "Start typing to see your post take shape…",
    votes: 1, comments: 0, tag, img, fresh: true,
  };

  const publish = async () => {
    if (!ready) return;
    if (!(typeof window !== "undefined" && window.__USER__)) { setErr("Please log in to post."); return; }
    setBusy(true); setErr("");
    try {
      const r = await fetch("/api/threads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sub, title, body }) });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) { setErr(j.error || "Could not post."); setBusy(false); return; }
      location.hash = "/community"; location.reload();
    } catch (e) { setErr("Network error — please try again."); setBusy(false); }
  };

  return (
    <div className="view compose">
      <div className="shell">
        <button className="back" onClick={() => go("community")}><Icon name="arrowLeft" size={16} /> Community</button>
        <div className="host-head">
          <span className="kicker">Post to iPanjab</span>
          <h1 className="serif">Start a thread.</h1>
        </div>

        <div className="host-grid">
          <form className="host-form" onSubmit={e => e.preventDefault()}>
            <CmpField label="Community" hint="Where should this live?">
              <div className="cmp-comms">
                {COMMUNITIES.map(c => (
                  <button key={c.id} type="button" className="cmp-comm" data-on={sub === c.name} onClick={() => setSub(c.name)}>
                    <span className="comm-badge" style={{ background: c.color }}>{c.name[0]}</span>
                    <span className="cmp-comm-txt"><b>{c.name}</b><span>{c.members} members</span></span>
                    {sub === c.name && <Icon name="check" size={16} className="cmp-comm-check" />}
                  </button>
                ))}
              </div>
            </CmpField>

            <CmpField label="Flair">
              <div className="host-chips">
                {POST_TAGS.map(tg => <button key={tg} type="button" className="chip" data-on={tag === tg} onClick={() => setTag(tg)}>{tg}</button>)}
              </div>
            </CmpField>

            <CmpField label="Title" hint={title.length + "/120"}>
              <input className="host-title-input" maxLength={120} placeholder="Ask a question, share a find, start a debate…" value={title} onChange={e => setTitle(e.target.value)} />
            </CmpField>

            <CmpField label="Body" hint="Optional — but context helps.">
              <textarea rows={6} placeholder="Say more. What happened, what you're asking, what you'd recommend…" value={body} onChange={e => setBody(e.target.value)} />
            </CmpField>

            <CmpField label="Attach">
              <button type="button" className="cmp-attach" data-on={img} onClick={() => setImg(!img)}>
                <Icon name={img ? "check" : "camera"} size={17} />
                {img ? "Image added" : "Add an image"}
              </button>
            </CmpField>
          </form>

          <aside className="host-preview">
            <div className="host-preview-sticky">
              <span className="kicker">Live preview</span>
              <div className="cmp-pv post-list">
                <PostRow post={preview} i={0} onOpen={() => {}} />
              </div>
              <button className="btn btn-primary host-publish" onClick={publish} disabled={busy || !ready}>
                <Icon name="bolt" size={17} /> {busy ? "Posting…" : "Post to community"}
              </button>
              {err && <p className="host-pv-note" style={{ color: "var(--accent)" }}>{err}</p>}
              <p className="host-pv-note">{!sub ? "Pick a community first." : title.trim().length <= 3 ? "Add a title to post." : "Looks good — share it with the sangat."}</p>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

window.NewPost = NewPost;
