/* CIRG website — Analytics, News, Contacts, Donate, Volunteer. Exported to window. */

/* Reusable INACTIVE form: every field disabled + an explanatory notice. */
function DisabledForm({ t, title, fields, submitLabel, noticeText }) {
  return (
    <form className="card form-card form-disabled" onSubmit={(e) => e.preventDefault()} aria-describedby="form-disabled-note">
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
        <h3 style={{ margin: 0, fontSize: 20, fontWeight: 500 }}>{title}</h3>
        <span className="badge badge-muted" style={{ whiteSpace: "nowrap" }}><Icon name="lock" size={13} /> {t.ui.inPrep}</span>
      </div>
      <div id="form-disabled-note"><Notice icon="info" text={noticeText} /></div>
      {fields.map((fl, i) => {
        if (fl.type === "textarea") return <label className="field" key={i}><span className="field-label">{fl.label}</span><textarea className="textarea" rows="3" disabled placeholder={fl.ph}></textarea></label>;
        if (fl.type === "select") return <label className="field" key={i}><span className="field-label">{fl.label}</span><select className="select" disabled defaultValue={fl.options[0]}>{fl.options.map((o) => <option key={o}>{o}</option>)}</select></label>;
        if (fl.type === "row") return (
          <div className="form-grid2" key={i}>
            {fl.cols.map((c, j) => <label className="field" key={j}><span className="field-label">{c.label}</span><input className="input" type={c.itype || "text"} disabled placeholder={c.ph} /></label>)}
          </div>
        );
        return <label className="field" key={i}><span className="field-label">{fl.label}</span><input className="input" type={fl.itype || "text"} disabled placeholder={fl.ph} /></label>;
      })}
      <label className="checkbox-row" style={{ opacity: 0.72 }}><input type="checkbox" disabled /><span>{t.contacts.consent}</span></label>
      <button className="btn btn-primary" type="submit" disabled>{submitLabel}</button>
    </form>
  );
}

/* ---------------- Analytics ---------------- */
function AnalyticsPage({ t, go }) {
  const a = t.analytics;
  const [cat, setCat] = React.useState(a.cats[0]);
  return (
    <main id="main">
      <PageIntro t={t} go={go} crumb={a.intro.eyebrow} eyebrow={a.intro.eyebrow} title={a.intro.title} lead={a.intro.lead} />
      <section className="section">
        <div className="container">
          <div className="search-filters" style={{ marginBottom: 32 }} role="group" aria-label={a.intro.eyebrow}>
            {a.cats.map((c) => <button key={c} className={"filter-chip" + (c === cat ? " on" : "")} aria-pressed={c === cat} onClick={() => setCat(c)}>{c}</button>)}
          </div>
          <div className="grid-3">
            {a.upcoming.map((u, i) => (
              <article className="card news-card" key={u.title}>
                <CardCover t={t} id={"an-" + i} h={150} />
                <div className="news-top">
                  <span className={"badge badge-" + u.tone}>{u.cat}</span>
                  <span className="badge badge-muted">{t.ui.soon}</span>
                </div>
                <h3>{u.title}</h3>
                <p>{u.text}</p>
                <button className="btn btn-secondary btn-sm" disabled style={{ alignSelf: "flex-start", marginTop: "auto" }}>{t.cta.willPublish}</button>
              </article>
            ))}
          </div>
          <div style={{ marginTop: 28 }}><Notice icon="bar-chart-3" text={t.placeholders.analytics} /></div>
        </div>
      </section>
      <section className="section" style={{ background: "var(--color-bg-soft-blue)", paddingBlock: "var(--section-pad-y-sm)" }}>
        <div className="container grid-2" style={{ gap: 48, alignItems: "center" }}>
          <div>
            <div className="eyebrow"><Icon name="mail" size={14} />{a.subscribeH}</div>
            <h2 style={{ marginTop: 12 }}>{a.subscribeH}</h2>
            <p className="lead">{a.subscribeText}</p>
          </div>
          <DisabledForm t={t} title={a.subscribeH} submitLabel={t.cta.subscribe}
            noticeText={t.placeholders.analytics}
            fields={[{ type: "input", label: "Email", itype: "email", ph: "you@hromada.ua" }]} />
        </div>
      </section>
    </main>
  );
}

/* ---------------- News ---------------- */
function NewsPage({ t, go }) {
  const n = t.news;
  const [cat, setCat] = React.useState(n.cats[0]);
  const list = cat === n.cats[0] ? n.items : n.items.filter((x) => x.cat === cat);
  return (
    <main id="main">
      <PageIntro t={t} go={go} crumb={n.intro.eyebrow} eyebrow={n.intro.eyebrow} title={n.intro.title} lead={n.intro.lead} />
      <section className="section">
        <div className="container">
          <div style={{ marginBottom: 24 }}><Notice icon="megaphone" text={t.placeholders.news} /></div>
          <div className="search-filters" style={{ marginBottom: 32 }} role="group" aria-label={n.intro.eyebrow}>
            {n.cats.map((c) => <button key={c} className={"filter-chip" + (c === cat ? " on" : "")} aria-pressed={c === cat} onClick={() => setCat(c)}>{c}</button>)}
          </div>
          {list.length ? (
            <div className="grid-3">
              {list.map((it) => (
                <article className="card news-card" key={it.title}>
                  <CardCover t={t} id={"news-" + t.news.items.indexOf(it)} h={150} />
                  <div className="news-top">
                    <span className={"badge badge-" + it.tone}>{it.cat}</span>
                    <span className="news-date">{it.date}</span>
                  </div>
                  <h3>{it.title}</h3>
                  <p>{it.text}</p>
                  <button className="btn btn-ghost btn-sm" disabled style={{ alignSelf: "flex-start", paddingInline: 0, marginTop: "auto" }}>{t.cta.readMore} <Icon name="arrow-right" size={15} /></button>
                </article>
              ))}
            </div>
          ) : <EmptyState icon="newspaper" text={t.search.empty} />}
        </div>
      </section>
    </main>
  );
}

/* ---------------- Contacts ---------------- */

// Approximate coordinates — replace with exact values when provided.
const MAP_OSTROH = [50.3271, 26.5156];
const MAP_ACADEMY = [50.3293839, 26.5228868];
const MAP_CIRG = [50.334317, 26.4958521];
const SHOW_ACADEMY = false; // academy hidden — set true to restore Ostroh Academy marker + legend on the map

function OsmMap({ t }) {
  const ref = React.useRef(null);
  const c = t.contacts;
  React.useEffect(() => {
    const el = ref.current;
    if (!window.L || !el || el._leaflet_id) return;
    const map = window.L.map(el, { scrollWheelZoom: false }).setView(MAP_OSTROH, 14);
    window.L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", {
      maxZoom: 19, subdomains: "abcd",
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/attributions">CARTO</a>',
    }).addTo(map);

    const pin = (color, icon) => window.L.divIcon({
      className: "cirg-pin-wrap",
      html: '<span class="cirg-pin" style="background:' + color + '"><i data-lucide="' + icon + '"></i></span>',
      iconSize: [32, 32], iconAnchor: [16, 32], tooltipAnchor: [0, -32],
    });
    if (SHOW_ACADEMY) {
      window.L.marker(MAP_ACADEMY, { icon: pin("var(--color-volunteer)", "graduation-cap") }).addTo(map)
        .bindTooltip(c.mapAcademy, { permanent: true, direction: "top", className: "cirg-tip cirg-tip-teal" });
    }
    window.L.marker(MAP_CIRG, { icon: pin("var(--color-action-blue)", "building-2") }).addTo(map)
      .bindTooltip(c.mapCirg, { permanent: true, direction: "top", className: "cirg-tip cirg-tip-blue" });
    if (window.lucide) window.lucide.createIcons();

    // Ostroh city boundary from OpenStreetMap (graceful if unavailable)
    fetch("https://nominatim.openstreetmap.org/search?format=geojson&polygon_geojson=1&limit=3&accept-language=uk&city=Ostroh&country=Ukraine")
      .then((r) => r.json())
      .then((data) => {
        const feat = (data.features || []).find((f) => f.geometry && /Polygon/.test(f.geometry.type));
        if (!feat) return;
        const layer = window.L.geoJSON(feat, { interactive: false, style: { color: "#2563EB", weight: 2, dashArray: "5 3", fillColor: "#2563EB", fillOpacity: 0.05 } }).addTo(map);
        try { map.fitBounds(layer.getBounds().pad(0.06)); } catch (e) {}
      })
      .catch(() => {});

    const ti = setTimeout(() => map.invalidateSize(), 250);
    return () => { clearTimeout(ti); map.remove(); };
  }, []);

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div ref={ref} className="cirg-map" role="region" aria-label={c.mapNote}></div>
      <div className="map-foot">
        <span className="mi"><Icon name="map-pin" size={13} color="var(--color-action-blue)" />{c.mapCirgFull}</span>
        {SHOW_ACADEMY ? <span className="mi"><Icon name="graduation-cap" size={13} color="var(--color-volunteer)" />{c.mapAcademyFull}</span> : null}
      </div>
    </div>
  );
}

function ContactsPage({ t, go }) {
  const c = t.contacts;
  return (
    <main id="main">
      <PageIntro t={t} go={go} crumb={c.intro.eyebrow} eyebrow={c.intro.eyebrow} title={c.intro.title} lead={c.intro.lead} />
      <section className="section">
        <div className="container grid-2" style={{ gap: 48, alignItems: "start" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {c.info.map((x) => (
              <div className="card" key={x[1]} style={{ display: "flex", gap: 16, alignItems: "center", padding: 22 }}>
                <span className="dir-ico" style={{ background: "var(--color-bg-soft-blue)", color: "var(--color-action-blue)" }}><Icon name={x[0]} size={22} /></span>
                <div><div className="dir-n">{x[1]}</div><div style={{ fontSize: 16, color: "var(--color-navy)", fontWeight: 500 }}>{x[2]}</div></div>
              </div>
            ))}
            <OsmMap t={t} />
            <div className="ftr-soc" style={{ marginTop: 4 }}>
              <a role="link" tabIndex="0" style={{ background: "var(--color-bg-soft-blue)", color: "var(--color-action-blue)" }} aria-label="Facebook"><Icon name="facebook" size={18} /></a>
              <a role="link" tabIndex="0" style={{ background: "var(--color-bg-soft-blue)", color: "var(--color-action-blue)" }} aria-label="LinkedIn"><Icon name="linkedin" size={18} /></a>
              <a role="link" tabIndex="0" style={{ background: "var(--color-bg-soft-blue)", color: "var(--color-action-blue)" }} aria-label="Telegram"><Icon name="send" size={18} /></a>
            </div>
          </div>
          <ContactForm t={t} title={c.formTitle} micro={c.formMicro} types={c.types} withOrg typeLabel={c.fields.type} />
        </div>
      </section>
    </main>
  );
}

/* ---------------- Donate ---------------- */
function DonatePage({ t, go }) {
  const d = t.donate;
  return (
    <main id="main">
      <PageIntro t={t} go={go} crumb={d.intro.eyebrow} eyebrow={d.intro.eyebrow} title={d.intro.title} lead={d.intro.lead} />
      <section className="section">
        <div className="container grid-2" style={{ gap: 48, alignItems: "start" }}>
          <div>
            <div className="eyebrow"><Icon name="heart" size={14} />{d.whyH.eyebrow}</div>
            <h2 style={{ marginTop: 12 }}>{d.whyH.title}</h2>
            <p className="lead">{d.why}</p>
            <div className="eyebrow" style={{ marginTop: 28 }}><Icon name="pie-chart" size={14} />{d.useH.eyebrow}</div>
            <h3 style={{ marginTop: 10, fontSize: "var(--fs-h3)" }}>{d.useH.title}</h3>
            <div className="grid-2" style={{ gap: 14 }}>
              {d.use.map((u) => (
                <div className="card" key={u[1]} style={{ display: "flex", gap: 14, alignItems: "flex-start", padding: 18 }}>
                  <span className="dir-ico" style={{ background: "var(--color-bg-soft-blue)", color: "var(--color-action-blue)", flex: "none", width: 44, height: 44 }}><Icon name={u[0]} size={20} /></span>
                  <div><b style={{ color: "var(--color-navy)", display: "block", fontSize: 15.5, marginBottom: 3 }}>{u[1]}</b><span style={{ fontSize: 13.5, color: "var(--color-text-secondary)" }}>{u[2]}</span></div>
                </div>
              ))}
            </div>
            <div className="card" style={{ marginTop: 18, display: "flex", gap: 14, alignItems: "flex-start" }}>
              <span className="dir-ico" style={{ background: "var(--color-volunteer-soft)", color: "var(--color-volunteer)", flex: "none", width: 44, height: 44 }}><Icon name="eye" size={20} /></span>
              <div><b style={{ color: "var(--color-navy)", display: "block", marginBottom: 3 }}>{d.transparencyH}</b><span style={{ fontSize: 14, color: "var(--color-text-secondary)" }}>{d.transparencyText}</span></div>
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div className="eyebrow"><Icon name="hand-heart" size={14} />{d.methodsH.eyebrow}</div>
            <h2 style={{ margin: 0 }}>{d.methodsH.title}</h2>
            <div className="donate-tiers" aria-hidden="true">
              {d.tiers.map((tr) => (
                <div className="tier" key={tr[0]}><div className="amt">{tr[0]}</div><div className="desc">{tr[1]}</div></div>
              ))}
            </div>
            <DisabledForm t={t} title={d.formTitle} submitLabel={t.cta.donate}
              noticeText={t.placeholders.payment}
              fields={[
                { type: "row", cols: [{ label: t.contacts.fields.name, ph: t.lang === "en" ? "Olena Kovalchuk" : "Олена Ковальчук" }, { label: "Email", itype: "email", ph: "you@hromada.ua" }] },
                { type: "row", cols: [{ label: t.lang === "en" ? "Amount, ₴" : "Сума, ₴", itype: "number", ph: "1000" }, { label: t.lang === "en" ? "Card number" : "Номер картки", ph: "0000 0000 0000 0000" }] },
              ]} />
          </div>
        </div>
      </section>
      <section className="section" style={{ background: "var(--color-bg-soft-blue)", paddingBlock: "var(--section-pad-y-sm)" }}>
        <div className="container">
          <div className="band band-navy">
            <div style={{ display: "flex", alignItems: "center", gap: 24, flexWrap: "wrap" }}>
              <div style={{ flex: 1, minWidth: 280 }}>
                <h2 style={{ marginBottom: 8, fontSize: "var(--fs-h3)", color: "#fff" }}>{t.home.transparency.supportSoft}</h2>
                <p style={{ margin: 0, color: "var(--color-text-on-dark-muted)" }}>{t.home.finalCta.lead}</p>
              </div>
              <button className="btn btn-lg" style={{ background: "#fff", color: "var(--color-action-blue)" }} onClick={() => go("partners")}>{t.cta.partner}</button>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ---------------- Volunteer ---------------- */
function VolunteerPage({ t, go }) {
  const v = t.volunteer;
  return (
    <main id="main">
      <PageIntro t={t} go={go} crumb={v.intro.eyebrow} eyebrow={v.intro.eyebrow} title={v.intro.title} lead={v.intro.lead} />
      <section className="section">
        <div className="container">
          <div style={{ marginBottom: 28 }}><Notice icon="hand-heart" tone="amber" text={t.placeholders.volunteer} /></div>
          <div className="grid-2" style={{ gap: 48, alignItems: "start" }}>
            <div>
              <div className="eyebrow"><Icon name="users" size={14} />{v.whoH.eyebrow}</div>
              <h2 style={{ marginTop: 12 }}>{v.whoH.title}</h2>
              <div className="value-grid" style={{ gridTemplateColumns: "1fr", marginBottom: 32 }}>
                {v.who.map((w) => <div className="value-chip" key={w}><span className="ic"><Icon name="check" size={18} /></span><span>{w}</span></div>)}
              </div>
              <div className="eyebrow"><Icon name="compass" size={14} />{v.dirsH.eyebrow}</div>
              <h3 style={{ marginTop: 10, fontSize: "var(--fs-h3)" }}>{v.dirsH.title}</h3>
              <div className="grid-2" style={{ gap: 14 }}>
                {v.dirs.map((dr) => (
                  <div className="card" key={dr[1]} style={{ display: "flex", flexDirection: "column", gap: 8, padding: 18 }}>
                    <span className="dir-ico" style={{ background: "var(--color-volunteer-soft)", color: "var(--color-volunteer)", width: 44, height: 44 }}><Icon name={dr[0]} size={20} /></span>
                    <b style={{ color: "var(--color-navy)", fontSize: 16 }}>{dr[1]}</b>
                    <span style={{ fontSize: 13.5, color: "var(--color-text-secondary)" }}>{dr[2]}</span>
                  </div>
                ))}
              </div>
            </div>
            <DisabledForm t={t} title={v.formTitle} submitLabel={t.cta.volunteer}
              noticeText={t.placeholders.volunteer}
              fields={[
                { type: "row", cols: [{ label: t.contacts.fields.name, ph: t.lang === "en" ? "Olena Kovalchuk" : "Олена Ковальчук" }, { label: "Email", itype: "email", ph: "you@hromada.ua" }] },
                { type: "select", label: v.dirsH.title, options: v.dirs.map((x) => x[1]) },
                { type: "textarea", label: t.contacts.fields.message, ph: t.contacts.formMicro },
              ]} />
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { DisabledForm, OsmMap, AnalyticsPage, NewsPage, ContactsPage, DonatePage, VolunteerPage });
