/* ============================================================
   The Carnation — Contribute studio
   Real, tailored intake for writers, photographers, tipsters,
   correspondents, and civic ambassadors. People do the work:
   draft, bio, section, media, and the lead come in ready to run.
   ============================================================ */

const CONTRIB = {
  write:        { kind: "article", kicker: "Write for us", h: "Pitch or submit a piece.", sub: "Bring an essay, a column, or a reported story. Draft it here. Byline and real editing included.", bodyLabel: "Your piece", bodyPh: "Write or paste the full draft. It does not have to be perfect. We edit." },
  story:        { kind: "article", kicker: "First person", h: "Tell your own story.", sub: "An account from someone who lives a block, runs a shop, or remembers a place. The city's record is made of these.", bodyLabel: "Your account", bodyPh: "Tell it in your own voice, in as much detail as you like." },
  photo:        { kind: "media", kicker: "Photo & video", h: "Show the city.", sub: "Photograph Alliance: Main Street, the events, the small stuff. Send a portfolio or a single great frame.", bodyLabel: "What does it show?", bodyPh: "Where, when, and what is happening in the frame." },
  tip:          { kind: "tip", kicker: "News tip", h: "Send a tip.", sub: "A new opening, a closing, a meeting worth covering, something changing on your street. Help us stay current.", bodyLabel: "What's happening?", bodyPh: "The more specific, the better. A link or two helps." },
  pitch:        { kind: "pitch", kicker: "Story pitch", h: "Pitch coverage.", sub: "See a story we are missing? Bring the lead, and if you like, a hand reporting it out.", bodyLabel: "Why does it matter now?", bodyPh: "What is the story, and why this moment?" },
  interview:    { kind: "interview", kicker: "Interview", h: "Offer an interview.", sub: "Offer yourself, or point us to someone the city should hear from. We bring the questions.", bodyLabel: "Why them, why now?", bodyPh: "Who they are and what makes them worth hearing from." },
  correspondent:{ kind: "corr", kicker: "Correspondent", h: "Cover a beat.", sub: "Keep an eye on a beat or a neighborhood over time. Loose, credited, and genuinely useful to the whole city.", bodyLabel: "Why you?", bodyPh: "The beat or neighborhood you would watch, and why you are the one to do it." },
  ambassador:   { kind: "amb", kicker: "Spread the word", h: "Become a Carnation Ambassador.", sub: "Help the city find its own publication. Introduce local businesses, bring readers, and grow the circle of support around independent local media." },
};
const CONTRIB_ORDER = ["write", "story", "photo", "tip", "pitch", "interview", "correspondent"];
const CONTRIB_SECTIONS = ["Business", "Spaces", "Culture", "Ideas", "Public Life"];
const AMB_HELP = ["Introduce local businesses", "Share with readers", "Host a reader meetup", "Help at events", "Post on social", "Connect us to a partner"];

function ContributePage({ type }) {
  const valid = CONTRIB[type] ? type : "write";
  const [t, setT] = useState(valid);
  useEffect(() => { setT(CONTRIB[type] ? type : "write"); window.scrollTo(0, 0); }, [type]);
  const cfg = CONTRIB[t];
  const isArticle = cfg.kind === "article";
  const isAmb = cfg.kind === "amb";

  const [sent, setSent] = useState(false);
  const [f, setF] = useState({ headline: "", dek: "", section: "Business", body: "", bio: "", seo: "", link: "", where: "", name: "", email: "", neighborhood: "" });
  const [tags, setTags] = useState([]);
  const [help, setHelp] = useState([]);
  const [photos, setPhotos] = useState([]);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const onPhotos = (e) => {
    const files = [...(e.target.files || [])]; e.target.value = "";
    files.slice(0, 4 - photos.length).forEach((file) => {
      if (!/^image\//.test(file.type)) return;
      const fr = new FileReader(); fr.onload = () => setPhotos((p) => [...p, fr.result].slice(0, 4)); fr.readAsDataURL(file);
    });
  };
  const toggleHelp = (x) => setHelp((a) => a.includes(x) ? a.filter((y) => y !== x) : [...a, x]);

  const submit = async (e) => {
    e.preventDefault();
    let ok;
    if (isAmb) {
      ok = await window.captureOrAlert("submissions", { type: "Ambassador", title: f.name || "Ambassador signup", body: f.body, name: f.name, email: f.email,
        ambassador: { neighborhood: f.neighborhood, help } });
    } else {
      ok = await window.captureOrAlert("submissions", { type: "Contribution: " + cfg.kicker, title: isArticle ? f.headline : (cfg.kicker), body: f.body, name: f.name, email: f.email,
        contribution: { kind: t, headline: f.headline, dek: f.dek, section: f.section, bio: f.bio, seo: f.seo, link: f.link, where: f.where, photos: photos.length } });
    }
    if (!ok) return;
    setSent(true); window.scrollTo(0, 0);
  };

  if (sent) {
    return (
      <main className="route">
        <section className="phead"><div className="wrap">
          <div className="phead__kick">{cfg.kicker}</div>
          <h1 className="phead__title">{isAmb ? "Welcome to the circle." : "It's in. Thank you."}</h1>
        </div></section>
        <section className="section section--tight"><div className="wrap wrap--narrow">
          <div className="sent">{isAmb
            ? <>Thanks for stepping up, <b>{f.name || "friend"}</b>. We will be in touch at <b>{f.email || "your email"}</b> with a short ambassador kit and the best ways to help.</>
            : <>We have your {cfg.kicker.toLowerCase()} and an editor will read it. If it is a fit, we will reach out at <b>{f.email || "your email"}</b>. Good work travels fast here.</>}</div>
          <div style={{marginTop:"22px", display:"flex", gap:"12px", flexWrap:"wrap"}}>
            <a className="btn btn--line" href="#/join">Back to Get Involved <span className="arw">→</span></a>
            <a className="btn btn--line" href="#/">The front page</a>
          </div>
        </div></section>
      </main>
    );
  }

  /* ---- shared contact fields ---- */
  const Contact = ({ optional }) => (
    <fieldset className="lsp-fieldset">
      <div className="lsp-fieldset__label"><span className="num">{isArticle ? "03" : "02"}</span> About you</div>
      <div className="lsp-grid2">
        <div className="frow"><label>Your name{optional ? " (optional)" : ""}</label><input className="input" value={f.name} onChange={set("name")} placeholder="How you'd like the byline to read" /></div>
        <div className="frow"><label>Email{optional ? " (optional)" : ""}</label><input className="input" type="email" required={!optional} value={f.email} onChange={set("email")} placeholder="So we can follow up" /></div>
      </div>
      {isArticle && <div className="frow"><label>Short bio <span className="note" style={{textTransform:"none",letterSpacing:0}}>· one or two lines, for your byline</span></label><input className="input" value={f.bio} onChange={set("bio")} placeholder="Who you are and your tie to Alliance" /></div>}
    </fieldset>
  );

  return (
    <main className="route">
      <section className="phead"><div className="wrap">
        <div className="phead__kick">{isAmb ? "Get Involved" : "Contribute"}</div>
        <h1 className="phead__title" style={{marginBottom:"14px"}}>{cfg.h}</h1>
        <p className="phead__dek" style={{margin:0}}>{cfg.sub}</p>
        {!isAmb && (
          <div className="lsp-seg" style={{marginTop:"22px"}}>
            {CONTRIB_ORDER.map((id) => (
              <button type="button" key={id} className={"chip" + (t === id ? " on" : "")} onClick={() => { setT(id); }}>{CONTRIB[id].kicker}</button>
            ))}
          </div>
        )}
        <hr className="rule rule--double phead__rule" style={{marginTop:"26px"}} />
      </div></section>

      <section className="section section--tint"><div className="wrap">
        <form className="form lsp-build" onSubmit={submit} style={isArticle ? {} : { gridTemplateColumns: "1fr" }}>
          <div className="lsp-form">

            {isArticle && <>
              <fieldset className="lsp-fieldset">
                <div className="lsp-fieldset__label"><span className="num">01</span> The piece</div>
                <div className="frow"><label>Headline</label><input className="input" required value={f.headline} onChange={set("headline")} placeholder="A clear, specific headline" /></div>
                <div className="frow"><label>Standfirst <span className="note" style={{textTransform:"none",letterSpacing:0}}>· the one-line summary under the headline</span></label><input className="input" value={f.dek} onChange={set("dek")} placeholder="Set up the piece in a sentence" /></div>
                <div className="frow"><label>Section</label>
                  <div className="lsp-seg">{CONTRIB_SECTIONS.map((s) => <button type="button" key={s} className={"chip" + (f.section === s ? " on" : "")} onClick={() => setF((x) => ({ ...x, section: s }))}>{s}</button>)}</div>
                </div>
              </fieldset>
              <fieldset className="lsp-fieldset">
                <div className="lsp-fieldset__label"><span className="num">02</span> {cfg.bodyLabel}</div>
                <div className="frow"><textarea className="textarea" required value={f.body} onChange={set("body")} placeholder={cfg.bodyPh} style={{minHeight:"260px"}} /></div>
                <div className="frow"><label>Suggested search description <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional, helps it get found</span></label><input className="input" value={f.seo} onChange={set("seo")} placeholder="One sentence describing the piece for search and social" /></div>
                <div className="frow"><label>Images <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional, up to 4</span></label>
                  <div className="lsp-photos">
                    {photos.map((src,i)=>(<div className="lsp-photo" key={i}><img src={src} alt="" /><button type="button" className="lsp-photo__x" onClick={()=>setPhotos((p)=>p.filter((_,j)=>j!==i))}>×</button></div>))}
                    {photos.length<4 && (<label className="lsp-add">+ Add image<input type="file" accept="image/*" multiple onChange={onPhotos} style={{display:"none"}} /></label>)}
                  </div>
                </div>
              </fieldset>
              <Contact />
            </>}

            {cfg.kind === "media" && <>
              <fieldset className="lsp-fieldset">
                <div className="lsp-fieldset__label"><span className="num">01</span> Your work</div>
                <div className="frow"><label>{cfg.bodyLabel}</label><textarea className="textarea" required value={f.body} onChange={set("body")} placeholder={cfg.bodyPh} /></div>
                <div className="frow"><label>Portfolio or a link <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional</span></label><input className="input" value={f.link} onChange={set("link")} placeholder="Instagram, website, or a folder" /></div>
                <div className="frow"><label>Attach frames <span className="note" style={{textTransform:"none",letterSpacing:0}}>· up to 4</span></label>
                  <div className="lsp-photos">
                    {photos.map((src,i)=>(<div className="lsp-photo" key={i}><img src={src} alt="" /><button type="button" className="lsp-photo__x" onClick={()=>setPhotos((p)=>p.filter((_,j)=>j!==i))}>×</button></div>))}
                    {photos.length<4 && (<label className="lsp-add">+ Add image<input type="file" accept="image/*" multiple onChange={onPhotos} style={{display:"none"}} /></label>)}
                  </div>
                </div>
              </fieldset>
              <Contact />
            </>}

            {(cfg.kind === "tip" || cfg.kind === "pitch" || cfg.kind === "interview" || cfg.kind === "corr") && <>
              <fieldset className="lsp-fieldset">
                <div className="lsp-fieldset__label"><span className="num">01</span> The details</div>
                {cfg.kind === "pitch" && <div className="frow"><label>Working headline</label><input className="input" value={f.headline} onChange={set("headline")} placeholder="The story in a line" /></div>}
                {cfg.kind === "interview" && <div className="frow"><label>Who should we talk to?</label><input className="input" required value={f.headline} onChange={set("headline")} placeholder="Name, or 'myself'" /></div>}
                {cfg.kind === "corr" && <div className="frow"><label>Your beat or neighborhood</label><input className="input" required value={f.headline} onChange={set("headline")} placeholder="e.g. Downtown, the schools, the arts scene" /></div>}
                <div className="frow"><label>{cfg.bodyLabel}</label><textarea className="textarea" required value={f.body} onChange={set("body")} placeholder={cfg.bodyPh} /></div>
                {(cfg.kind === "tip") && <div className="frow"><label>Where <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional</span></label><input className="input" value={f.where} onChange={set("where")} placeholder="Address or part of town" /></div>}
                {(cfg.kind === "tip" || cfg.kind === "interview" || cfg.kind === "corr") && <div className="frow"><label>A link <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional</span></label><input className="input" value={f.link} onChange={set("link")} placeholder={cfg.kind === "corr" ? "A writing sample, if you have one" : "Anything that helps"} /></div>}
              </fieldset>
              <Contact optional={cfg.kind === "tip"} />
            </>}

            {isAmb && <>
              <fieldset className="lsp-fieldset">
                <div className="lsp-fieldset__label"><span className="num">01</span> How you'd help</div>
                <div className="frow"><label>Pick what fits</label>
                  <div className="lsp-seg">{AMB_HELP.map((x) => <button type="button" key={x} className={"chip" + (help.includes(x) ? " on" : "")} onClick={() => toggleHelp(x)}>{x}</button>)}</div>
                </div>
                <div className="frow"><label>Anything you want us to know <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional</span></label><textarea className="textarea" value={f.body} onChange={set("body")} placeholder="Businesses you know, rooms you can fill, people you can reach." /></div>
              </fieldset>
              <fieldset className="lsp-fieldset">
                <div className="lsp-fieldset__label"><span className="num">02</span> About you</div>
                <div className="lsp-grid2">
                  <div className="frow"><label>Your name</label><input className="input" required value={f.name} onChange={set("name")} placeholder="So we can thank you properly" /></div>
                  <div className="frow"><label>Email</label><input className="input" type="email" required value={f.email} onChange={set("email")} placeholder="Where we send the kit" /></div>
                </div>
                <div className="frow"><label>Your part of town <span className="note" style={{textTransform:"none",letterSpacing:0}}>· optional</span></label><input className="input" value={f.neighborhood} onChange={set("neighborhood")} placeholder="Neighborhood or nearby" /></div>
              </fieldset>
            </>}

            <div style={{display:"flex",gap:"14px",alignItems:"center",flexWrap:"wrap"}}>
              <button className="btn btn--red btn--lg" type="submit">{isAmb ? "Count me in" : "Send to the newsroom"} <span className="arw">→</span></button>
              <span className="note">{isAmb ? "No fees, no quotas. Recognition, not commission." : "An editor reads everything that comes in."}</span>
            </div>
          </div>

          {isArticle && (
            <aside className="lsp-aside">
              <div className="lsp-aside__label">How it would run</div>
              <div className="profile" style={{cursor:"default"}}>
                <div className="profile__body" style={{padding:"clamp(20px,2.4vw,28px)"}}>
                  <div className="profile__cat">{f.section}</div>
                  <h3 className="card__title" style={{fontSize:"clamp(1.4rem,2.4vw,1.9rem)", margin:"4px 0 10px"}}>{f.headline || "Your headline appears here"}</h3>
                  <p className="card__dek" style={{marginBottom:"14px"}}>{f.dek || "Your standfirst sets up the piece in a single line."}</p>
                  <div className="byline" style={{marginBottom:"16px"}}><span>By {f.name || "your name"}</span></div>
                  <p className="profile__blurb" style={{whiteSpace:"pre-wrap"}}>{f.body ? (f.body.length > 280 ? f.body.slice(0, 280) + "…" : f.body) : "The opening of your piece previews here as you write, set the way it would appear in The Carnation."}</p>
                </div>
              </div>
              {f.bio && <p className="note" style={{marginTop:"14px"}}>{f.bio}</p>}
            </aside>
          )}
        </form>
      </div></section>
    </main>
  );
}

window.ContributePage = ContributePage;
