/* ============================================================
   iPanjab — New post composer (text only) + edit mode
   ============================================================ */

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, editId }) {
  const editing = editId ? ((typeof POSTS !== "undefined" ? POSTS : []).find(p => p.id === editId) || null) : null;
  const [sub, setSub] = useState(editing ? editing.sub : (presetSub || ""));
  const [tag, setTag] = useState(editing ? (editing.tag || "Discussion") : "Discussion");
  const [title, setTitle] = useState(editing ? editing.title : "");
  const [body, setBody] = useState(editing ? (editing.body || "") : "");
  const [city, setCity] = useState(editing ? (editing.city || "") : "");
  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: editing ? editing.author : "you",
    time: editing ? editing.time : "now",
    title: title || "Your post title will appear here",
    body: body || "Start typing to see your post take shape…",
    votes: editing ? editing.votes : 1, comments: editing ? editing.comments : 0, tag, 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 url = editing ? "/api/threads/update" : "/api/threads";
      const payload = editing ? { id: editing._id, title, body, city } : { sub, title, body, city };
      const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) { setErr(j.error || "Could not save."); setBusy(false); return; }
      location.hash = editing ? ("/community/" + editing.id) : "/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(editing ? ("community/" + editing.id) : "community")}><Icon name="arrowLeft" size={16} /> {editing ? "Post" : "Community"}</button>
        <div className="host-head">
          <span className="kicker">{editing ? "Editing your post" : "Post to iPanjab"}</span>
          <h1 className="serif">{editing ? "Edit your post." : "Start a thread."}</h1>
        </div>

        <div className="host-grid">
          <form className="host-form" onSubmit={e => e.preventDefault()}>
            {!editing && (
            <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>
            )}

            {!editing && (
            <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="City (optional)" hint="Tag your post to a place"><input className="host-title-input" placeholder="e.g. Brampton, Surrey, Southall" value={city} onChange={e => setCity(e.target.value)} /></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={editing ? "check" : "bolt"} size={17} /> {busy ? "Saving…" : (editing ? "Save changes" : "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." : (editing ? "Update and save." : "Looks good — share it with the sangat.")}</p>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

window.NewPost = NewPost;
