// Sarpah — audience pages, section indices, forms

const { useEffect, useMemo, useState, useRef } = React;
const S2 = window.Sarpah;
const SP = window.SarpahPages;
const Arrow2 = S2.Arrow;

/* ============================================================
   Audience pages — Buyers / Originators / Sub-agents
   These render their underlying markdown but with a richer hero & CTAs.
   ============================================================ */

function AudiencePage({ route, eyebrow, accentVerb, ctaSlug, ctaLabel }) {
  const md = S2.useMarkdown(route.file);
  const imgKey = window.SarpahImg.pickFor(route);
  return (
    <>
      <section className="page-head page-head--photo">
        <div className="page-head__bg" style={{backgroundImage: `url(${window.SarpahImg.urlFor(imgKey, 2000, 80)})`}} aria-hidden="true" />
        <div className="page-head__scrim" aria-hidden="true" />
        <div className="page-head__inner page-head__inner--photo" style={{maxWidth: 1360}}>
          <SP.Crumbs trail={SP.buildTrail(route)} />
          <div className="ribbon ribbon--on-photo">{eyebrow}</div>
          <h1 className="page-head__title page-head__title--on-photo" style={{fontSize: "clamp(48px, 6vw, 88px)"}}>{route.title}</h1>
          <p className="page-head__lede page-head__lede--on-photo" style={{maxWidth: "44ch"}}>{route.description}</p>
          <div style={{marginTop: 24, display: "flex", gap: 12, flexWrap: "wrap"}}>
            <a href={"#" + ctaSlug} className="btn btn--accent btn--lg">{ctaLabel} <Arrow2/></a>
            <a href="#/about" className="btn btn--lg btn--on-photo">About Sarpah <Arrow2/></a>
          </div>
        </div>
      </section>
      <div className="body-two-col">
        <aside className="toc-side no-print">
          {md.headings && md.headings.length > 0 && <>
            <h4>On this page</h4>
            <ul>
              {md.headings.filter(h => h.level === 2).map(h => (
                <li key={h.id}><a href="#" onClick={(e) => { e.preventDefault(); document.getElementById(h.id)?.scrollIntoView({behavior:"smooth", block:"start"}); }}>{h.text}</a></li>
              ))}
            </ul>
          </>}
          <h4 style={{marginTop: 24}}>Open a file</h4>
          <ul>
            <li><a href={"#" + ctaSlug}>{ctaLabel} →</a></li>
          </ul>
        </aside>
        <article>
          {md.html && <div className="prose" dangerouslySetInnerHTML={{__html: md.html}} />}
        </article>
      </div>
    </>
  );
}

/* ============================================================
   Section index pages
   ============================================================ */

function ProductsIndex({ route }) {
  const groups = ["Fertilizers", "Grain", "Edible Oils", "Food", "Petroleum", "Timber"];
  const overview = window.SARPAH_ROUTES.find(r => r.section === "products" && r.group === route.group && r.order === 0);
  const md = S2.useMarkdown(overview && overview.generated ? null : (overview ? overview.file : null));

  const groupItems = window.SARPAH_ROUTES.filter(r => r.section === "products" && r.group === route.group && !(r.order === 0));
  const imgKey = window.SarpahImg.pickFor(route);

  return (
    <>
      <SP.PageHead route={route} photo={imgKey} />
      <SP.SectionNav route={route} />
      <section className="section">
        <div className="container">
          {md.html && <div className="prose" style={{maxWidth: "var(--measure)", marginBottom: 56}} dangerouslySetInnerHTML={{__html: md.html}} />}
          {groupItems.length > 0 && (
            <div className="card-grid">
              {groupItems.map(r => (
                <a key={r.slug} href={"#" + r.slug} className="card">
                  <span className="tag">{route.group}</span>
                  <h4 className="card__title">{r.title}</h4>
                  <p className="card__desc">{r.description}</p>
                  <div className="card__foot"><span>Open brief</span> <Arrow2/></div>
                </a>
              ))}
            </div>
          )}
        </div>
      </section>
    </>
  );
}

function FoodIndex({ route }) {
  // Synthetic: no overview .md, list items
  const items = window.SARPAH_ROUTES.filter(r => r.section === "products" && r.group === "Food" && !r.generated);
  return (
    <>
      <SP.PageHead route={route} photo="warehouse-pallets" />
      <SP.SectionNav route={route} />
      <section className="section">
        <div className="container">
          <div className="prose" style={{marginBottom: 56}}>
            <p>Sarpah’s food line is deliberately narrow. Two material flows: <strong>dry milk</strong> for institutional reconstitution and the <strong>sugar</strong> complex — Icumsa 45 refined, VHP raws and brown — moving on Brazilian / South American origin terms into the East African market. We do not retail; every flow is bagged, palletised and contracted to the importer.</p>
          </div>
          <div className="card-grid">
            {items.map(r => (
              <a key={r.slug} href={"#" + r.slug} className="card">
                <span className="tag">Food</span>
                <h4 className="card__title">{r.title}</h4>
                <p className="card__desc">{r.description}</p>
                <div className="card__foot"><span>Open brief</span> <Arrow2/></div>
              </a>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

function ComplianceIndex({ route }) {
  const md = S2.useMarkdown(route.file);
  const items = window.SARPAH_ROUTES.filter(r => r.section === "compliance" && r.slug !== "/compliance");
  return (
    <>
      <SP.PageHead route={route} photo="documents-desk" />
      <SP.SectionNav route={route} />
      <section className="section">
        <div className="container">
          {md.html && <div className="prose" style={{marginBottom: 56}} dangerouslySetInnerHTML={{__html: md.html}} />}
          <div className="card-grid">
            {items.map(r => (
              <a key={r.slug} href={"#" + r.slug} className="card">
                <span className="tag tag--navy">Standard</span>
                <h4 className="card__title">{r.title}</h4>
                <p className="card__desc">{r.description}</p>
                <div className="card__foot"><span>Open standard</span> <Arrow2/></div>
              </a>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

function CorridorsIndex({ route }) {
  const md = S2.useMarkdown(route.file);
  const items = window.SARPAH_ROUTES.filter(r => r.section === "origination" && r.slug !== "/origination");
  return (
    <>
      <SP.PageHead route={route} photo="ship-bow-water" />
      <SP.SectionNav route={route} />
      <section className="section">
        <div className="container-wide">
          <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "center", marginBottom: 56}}>
            <div className="prose" style={{maxWidth: "100%"}}>
              {md.html && <div dangerouslySetInnerHTML={{__html: md.html}} />}
            </div>
            <figure className="corridor-photo">
              <div className="corridor-photo__img"
                   style={{backgroundImage: `url(${window.SarpahImg.urlFor("ship-bow-water", 1400, 80)})`}}
                   role="img" aria-label="Cargo ship under way" />
              <figcaption>
                <span className="ribbon ribbon--inline">Origination → Destination</span>
                <p>Russia–CIS load ports — Black Sea, Baltic, Caspian, Far East — discharging at Mombasa and Dar es Salaam for the EAC inland network.</p>
              </figcaption>
            </figure>
          </div>
          <div className="card-grid card-grid--2">
            {items.map(r => {
              const slugKey = r.slug.replace(/^\//, "").replace(/\//g, "-");
              const imgKey = window.SarpahImg.SECTION_HERO[slugKey] || "ship-bow-water";
              return (
                <a key={r.slug} href={"#" + r.slug} className="card card--photo">
                  <div className="card__photo" style={{backgroundImage: `url(${window.SarpahImg.urlFor(imgKey, 900, 75)})`}} aria-hidden="true" />
                  <div className="card__body">
                    <span className="tag tag--accent">Corridor</span>
                    <h4 className="card__title" style={{fontSize: "var(--t-2xl)"}}>{r.title}</h4>
                    <p className="card__desc">{r.description}</p>
                    <div className="card__foot"><span>Open corridor brief</span> <Arrow2/></div>
                  </div>
                </a>
              );
            })}
          </div>
        </div>
      </section>
    </>
  );
}

/* ============================================================
   Forms — multi-step with validation
   ============================================================ */

const FORM_DEFS = {
  buyer: {
    title: "Buyer enquiry",
    eyebrow: "For East African institutional buyers",
    asideTitle: "What happens next",
    asideBody: "Within one Malindi business day we acknowledge receipt and outline a working file: indicative spec, target lift window, Incoterms, and the documentary route (UCP 600 DLC, URDG 758 bond if a tender). Sarpah then routes the enquiry to the suitable origination corridor.",
    steps: [
      {
        title: "Your organisation",
        fields: [
          { name: "company", label: "Organisation name", required: true, type: "text", placeholder: "e.g. Mombasa Maize Millers Ltd." },
          { name: "country", label: "Country", required: true, type: "select", options: ["Kenya", "Tanzania", "Uganda", "Rwanda", "Burundi", "South Sudan", "DRC (Southern)", "Ethiopia", "Other EAC / Horn"] },
          { name: "role", label: "Your role", required: true, type: "text", placeholder: "Procurement Director, Tender Secretary…" },
          { name: "name", label: "Your name", required: true, type: "text" },
          { name: "email", label: "Work email", required: true, type: "email", validate: "email" },
          { name: "phone", label: "Phone (E.164)", type: "tel", placeholder: "+254 …" },
        ],
      },
      {
        title: "What you want to buy",
        fields: [
          { name: "category", label: "Category", required: true, type: "radio",
            options: [
              { v:"fertilizer", l:"Fertilizer", h:"Urea, NPK, DAP, MOP, SOP…" },
              { v:"grain",      l:"Grain",      h:"Wheat, barley, maize, peas, rice." },
              { v:"oils",       l:"Edible oils", h:"Sunflower, rapeseed, palm." },
              { v:"food",       l:"Food",       h:"Dry milk, sugar." },
              { v:"petroleum",  l:"Petroleum",  h:"Petcoke, technical sulphur." },
              { v:"timber",     l:"Timber",     h:"Plywood, OSB, sawn softwood." },
            ]
          },
          { name: "product", label: "Specific product / spec", required: true, type: "text", placeholder: "e.g. Wheat 12.5% protein FOSFA, ISO 7970" },
          { name: "tonnage", label: "Tonnage (MT)", required: true, type: "number", placeholder: "e.g. 25 000" },
          { name: "shipments", label: "Shipment structure", type: "radio",
            options: [
              { v:"single", l:"Single shipment", h:"One bill of lading." },
              { v:"frame",  l:"Frame contract",  h:"Multi-shipment over 6–12 months." },
              { v:"tender", l:"Tender bid",      h:"NCPB / KTDA / NFSP / EABL." },
            ]
          },
        ],
      },
      {
        title: "Documentary structure",
        fields: [
          { name: "incoterms", label: "Preferred Incoterms 2020", required: true, type: "select", options: ["CFR Mombasa", "CIF Mombasa", "CFR Dar es Salaam", "FOB origin", "DAP inland", "Other / discuss"] },
          { name: "payment", label: "Payment instrument", required: true, type: "radio",
            options: [
              { v:"dlc",    l:"Documentary credit (UCP 600)", h:"Confirmed at the buyer’s bank." },
              { v:"sblc",   l:"Standby (ISP98 / SBLC)",         h:"Frame contracts, multi-shipment." },
              { v:"urdg",   l:"URDG 758 bond + DLC",            h:"Tender-driven, e.g. NCPB." },
              { v:"discuss", l:"Discuss",                       h:"We propose a structure." },
            ]
          },
          { name: "lift", label: "Target lift window", type: "text", placeholder: "e.g. Q2-26 or 60 days from LC issuance" },
          { name: "notes", label: "Anything else we should know", type: "textarea", placeholder: "Tender reference, vessel size constraints, port of discharge, end-use, KEBS notes…" },
        ],
      },
      {
        title: "Confirm",
        confirm: true,
      },
    ],
  },
  mandate: {
    title: "Mandate enquiry",
    eyebrow: "For upstream originators & traders",
    asideTitle: "What happens next",
    asideBody: "We countersign an NCNDA / IMFPA pack within 24 hours, scope the East African leg, and schedule a working call to align on instruments, fees and corridor mechanics. Sarpah does not engage on principal–principal terms — we operate strictly as a mandated agent on the East African side.",
    steps: [
      {
        title: "Originator",
        fields: [
          { name: "company", label: "Producer / trading house", required: true, type: "text" },
          { name: "country", label: "Country / corridor", required: true, type: "text", placeholder: "Russia, Kazakhstan, Romania…" },
          { name: "role", label: "Your role", required: true, type: "text", placeholder: "Director, Mandate Holder…" },
          { name: "name", label: "Your name", required: true, type: "text" },
          { name: "email", label: "Work email", required: true, type: "email", validate: "email" },
          { name: "website", label: "Website", type: "url" },
        ],
      },
      {
        title: "Mandate scope",
        fields: [
          { name: "category", label: "Commodity category", required: true, type: "radio",
            options: [
              { v:"fertilizer", l:"Fertilizer" },
              { v:"grain",      l:"Grain" },
              { v:"oils",       l:"Edible oils" },
              { v:"food",       l:"Food (dry milk, sugar)" },
              { v:"petroleum",  l:"Petroleum (petcoke, sulphur)" },
              { v:"timber",     l:"Timber" },
            ]
          },
          { name: "products", label: "Specific products / specs", required: true, type: "textarea", placeholder: "e.g. Urea Grade B GOST 2081-2010, prilled and granular; up to 60 000 MT/month ex Novorossiysk…" },
          { name: "loadports", label: "Load ports / corridors", type: "text", placeholder: "Novorossiysk, Taman, Vysotsk, Aktau…" },
          { name: "monthly", label: "Monthly capacity (MT)", type: "number", placeholder: "e.g. 30 000" },
        ],
      },
      {
        title: "Documents in hand",
        fields: [
          { name: "docs", label: "What you can present", required: true, type: "checkbox",
            options: [
              { v:"contract",   l:"Producer / refinery contract" },
              { v:"soa",        l:"SCO / SOA (Soft Corporate Offer)" },
              { v:"ncnda",      l:"Signed NCNDA pack" },
              { v:"imfpa",      l:"IMFPA fee schedule" },
              { v:"compliance", l:"Sanctions / OFAC / OFSI position" },
              { v:"references", l:"Past performance references" },
            ]
          },
          { name: "exclusivity", label: "Exclusivity sought in EAC", type: "radio",
            options: [
              { v:"none", l:"Non-exclusive" },
              { v:"kenya", l:"Exclusive — Kenya only" },
              { v:"eac", l:"Exclusive — full EAC + Southern DRC" },
            ]
          },
          { name: "notes", label: "Notes", type: "textarea" },
        ],
      },
      { title: "Confirm", confirm: true },
    ],
  },
  "sub-agent": {
    title: "Sub-agent application",
    eyebrow: "Mandated representatives — EAC & Southern DRC",
    asideTitle: "What we look for",
    asideBody: "Local presence in a tender-relevant city (Mombasa, Nairobi, Kampala, Dar, Lubumbashi). One verifiable institutional reference. Track record on documentary instruments. Sub-agents work under a written sub-mandate; fees are paid on irrevocable IMFPA terms after corridor settlement.",
    steps: [
      {
        title: "About you",
        fields: [
          { name: "name", label: "Your name", required: true, type: "text" },
          { name: "company", label: "Company (if any)", type: "text" },
          { name: "city", label: "City of operation", required: true, type: "text", placeholder: "Mombasa, Lubumbashi, Kampala…" },
          { name: "country", label: "Country", required: true, type: "select", options: ["Kenya", "Tanzania", "Uganda", "Rwanda", "Burundi", "South Sudan", "DRC", "Ethiopia", "Other"] },
          { name: "email", label: "Email", required: true, type: "email", validate: "email" },
          { name: "phone", label: "Phone", required: true, type: "tel" },
        ],
      },
      {
        title: "Track record",
        fields: [
          { name: "experience", label: "Years in commodity / institutional procurement", required: true, type: "select", options: ["< 2", "2–5", "5–10", "10+"] },
          { name: "categories", label: "Categories you can introduce", required: true, type: "checkbox",
            options: [
              { v:"fertilizer", l:"Fertilizer (NCPB, KTDA, NFSP, FAFB-licensed)" },
              { v:"grain",      l:"Grain (millers, NCPB, EABL)" },
              { v:"oils",       l:"Edible oils (refiners)" },
              { v:"food",       l:"Food (institutional)" },
              { v:"petroleum",  l:"Petroleum (anode, technical sulphur)" },
              { v:"timber",     l:"Timber (construction merchants)" },
            ]
          },
          { name: "buyers", label: "Two institutional contacts you can name now", type: "textarea", placeholder: "We will keep this confidential. Format: Organisation — role of contact." },
        ],
      },
      {
        title: "Acknowledgement",
        fields: [
          { name: "ndaPack", label: "I agree to execute a Sarpah NCNDA + sub-mandate before any working file is shared", required: true, type: "checkbox-single" },
          { name: "imfpaPack", label: "I understand fees flow under IMFPA after corridor settlement, not on introduction", required: true, type: "checkbox-single" },
          { name: "exclusivity", label: "I will not parallel-channel a buyer to a competing originator on the same product line", required: true, type: "checkbox-single" },
        ],
      },
      { title: "Confirm", confirm: true },
    ],
  },
};

function FormPage({ route }) {
  const def = FORM_DEFS[route.form];
  const [step, setStep] = useState(0);
  const [data, setData] = useState({});
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [refNo, setRefNo] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const turnstileRef = useRef(null);
  const turnstileWidgetId = useRef(null);

  const total = def.steps.length;
  const cur = def.steps[step];

  useEffect(() => {
    if (!cur.confirm || !turnstileRef.current) return;
    const sitekey = window.SARPAH_TURNSTILE_SITEKEY;
    if (!sitekey) return;
    let cancelled = false;
    function tryRender() {
      if (cancelled) return;
      if (window.turnstile && turnstileRef.current && turnstileWidgetId.current === null) {
        turnstileWidgetId.current = window.turnstile.render(turnstileRef.current, {
          sitekey,
          theme: "light",
          action: "form-" + route.form,
        });
      } else if (!window.turnstile) {
        setTimeout(tryRender, 200);
      }
    }
    tryRender();
    return () => {
      cancelled = true;
      if (window.turnstile && turnstileWidgetId.current !== null) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch(_) {}
        turnstileWidgetId.current = null;
      }
    };
  }, [cur.confirm, route.form]);

  function set(name, value) {
    setData(d => ({...d, [name]: value}));
    setErrors(e => ({...e, [name]: undefined}));
  }
  function toggleArr(name, value) {
    setData(d => {
      const cur = Array.isArray(d[name]) ? d[name] : [];
      return {...d, [name]: cur.includes(value) ? cur.filter(x => x !== value) : [...cur, value]};
    });
    setErrors(e => ({...e, [name]: undefined}));
  }
  function validate() {
    if (cur.confirm) return true;
    const errs = {};
    for (const f of cur.fields) {
      const v = data[f.name];
      if (f.type === "checkbox-single") {
        if (f.required && !v) errs[f.name] = "Please confirm.";
        continue;
      }
      if (f.type === "checkbox") {
        if (f.required && (!Array.isArray(v) || v.length === 0)) errs[f.name] = "Pick at least one.";
        continue;
      }
      if (f.required && (!v || String(v).trim() === "")) {
        errs[f.name] = "Required.";
        continue;
      }
      if (v && f.validate === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) {
        errs[f.name] = "Doesn’t look like an email.";
      }
    }
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }
  function next() {
    if (!validate()) return;
    if (step < total - 1) {
      setStep(step + 1);
      window.scrollTo({top: 0, behavior: "smooth"});
    }
  }
  function prev() {
    if (step > 0) setStep(step - 1);
  }
  async function submit(e) {
    e.preventDefault();
    if (!validate()) return;
    if (submitting) return;
    const turnstileToken = window.turnstile && turnstileWidgetId.current !== null
      ? window.turnstile.getResponse(turnstileWidgetId.current)
      : "";
    if (!turnstileToken) {
      setSubmitError("Please complete the security check below.");
      return;
    }
    setSubmitting(true);
    setSubmitError("");
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ formType: route.form, data, turnstileToken }),
      });
      const result = await res.json().catch(() => ({}));
      if (!res.ok || !result.success) {
        throw new Error(result.error || "submit_failed");
      }
      setRefNo(result.refNo);
      setSubmitted(true);
      window.scrollTo({top: 0, behavior: "smooth"});
    } catch (err) {
      setSubmitError("Send failed. Please email us directly — see contact details on the About page.");
      if (window.turnstile && turnstileWidgetId.current !== null) {
        try { window.turnstile.reset(turnstileWidgetId.current); } catch(_) {}
      }
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted) {
    return (
      <>
        <SP.PageHead route={route} />
        <div className="container-narrow">
          <div className="form-card form-success" style={{marginTop: 48}}>
            <div className="ribbon" style={{justifyContent: "center", marginBottom: 16}}>Received</div>
            <h2 className="display" style={{fontSize: "var(--t-3xl)"}}>Thank you. Sarpah has the file.</h2>
            <p style={{maxWidth: "44ch", margin: "16px auto", color: "var(--ink-2)"}}>
              We will acknowledge by email within one Malindi business day. Quote the reference below in any reply.
            </p>
            <div className="form-success__ref">{refNo}</div>
            <div style={{display: "flex", gap: 12, justifyContent: "center", marginTop: 24, flexWrap: "wrap"}}>
              <a href="#/" className="btn">Back to Sarpah <Arrow2/></a>
              <a href="#/about" className="btn btn--ghost">Read about Sarpah <Arrow2/></a>
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <SP.PageHead route={route} eyebrow={def.eyebrow} />
      <div className="form-shell">
        <aside className="form-aside">
          <div className="ribbon">{def.eyebrow}</div>
          <h3>{def.asideTitle}</h3>
          <p>{def.asideBody}</p>
          <div className="form-stages">
            {def.steps.map((s, i) => (
              <div key={i} className={
                "form-stages__seg" +
                (i < step ? " is-done" : "") +
                (i === step ? " is-active" : "")
              }/>
            ))}
          </div>
          <div className="form-stages__caption">
            Step {step + 1} of {total} · {cur.title}
          </div>
        </aside>
        <form className="form-card" onSubmit={submit} noValidate>
          <h3 className="display" style={{fontSize: "var(--t-2xl)", marginTop: 0, marginBottom: 24}}>{cur.title}</h3>

          {cur.confirm ? (
            <div>
              <p style={{color:"var(--ink-2)"}}>Review what you’ve told us. Edit by going back; submit to open a working file.</p>
              <dl className="spec-sheet" style={{marginTop: 24}}>
                {Object.entries(data).map(([k, v]) => (
                  <React.Fragment key={k}>
                    <dt>{k.replace(/([A-Z])/g," $1")}</dt>
                    <dd>{Array.isArray(v) ? v.join(", ") : (typeof v === "boolean" ? (v?"Yes":"No") : String(v))}</dd>
                  </React.Fragment>
                ))}
              </dl>
              <div ref={turnstileRef} style={{marginTop: 32}} />
              {submitError && (
                <div role="alert" style={{marginTop: 16, padding: "12px 16px", background: "rgba(192, 138, 62, 0.12)", border: "1px solid rgba(192, 138, 62, 0.4)", color: "var(--ink-1)", fontSize: 14}}>
                  {submitError}
                </div>
              )}
            </div>
          ) : (
            <div className="fieldset">
              {cur.fields.map(f => <Field key={f.name} f={f} value={data[f.name]} error={errors[f.name]} set={set} toggleArr={toggleArr} />)}
            </div>
          )}

          <div className="form-actions">
            {step > 0 ? (
              <button type="button" className="btn btn--ghost" onClick={prev}>← Back</button>
            ) : <span className="step-meta">Open a Sarpah working file</span>}
            {step < total - 1 ? (
              <button type="button" className="btn" onClick={next}>Continue <Arrow2/></button>
            ) : (
              <button type="submit" className="btn btn--accent" disabled={submitting}>
                {submitting ? "Sending…" : <>Submit enquiry <Arrow2/></>}
              </button>
            )}
          </div>
        </form>
      </div>
    </>
  );
}

function Field({ f, value, error, set, toggleArr }) {
  const id = "f-" + f.name;
  return (
    <div className={"field" + (error ? " is-error" : "")}>
      {f.type !== "checkbox-single" && (
        <label htmlFor={id}>
          <span>{f.label}{f.required && <span className="req"> *</span>}</span>
          {error && <span className="error-msg">{error}</span>}
        </label>
      )}
      {(f.type === "text" || f.type === "email" || f.type === "tel" || f.type === "url" || f.type === "number") && (
        <input id={id} type={f.type} value={value || ""} placeholder={f.placeholder || ""}
               onChange={e => set(f.name, e.target.value)} />
      )}
      {f.type === "textarea" && (
        <textarea id={id} value={value || ""} placeholder={f.placeholder || ""} rows={4}
                  onChange={e => set(f.name, e.target.value)} />
      )}
      {f.type === "select" && (
        <select id={id} value={value || ""} onChange={e => set(f.name, e.target.value)}>
          <option value="">Select…</option>
          {f.options.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      )}
      {f.type === "radio" && (
        <div className="radio-group">
          {f.options.map(o => (
            <label key={o.v} className={"choice" + (value === o.v ? " is-checked" : "")}>
              <input type="radio" name={f.name} value={o.v} checked={value === o.v} onChange={() => set(f.name, o.v)} />
              <div>
                <div className="choice__label">{o.l}</div>
                {o.h && <div className="choice__hint">{o.h}</div>}
              </div>
            </label>
          ))}
        </div>
      )}
      {f.type === "checkbox" && (
        <div className="checkbox-group">
          {f.options.map(o => {
            const arr = Array.isArray(value) ? value : [];
            const checked = arr.includes(o.v);
            return (
              <label key={o.v} className={"choice" + (checked ? " is-checked" : "")}>
                <input type="checkbox" checked={checked} onChange={() => toggleArr(f.name, o.v)} />
                <div>
                  <div className="choice__label">{o.l}</div>
                  {o.h && <div className="choice__hint">{o.h}</div>}
                </div>
              </label>
            );
          })}
        </div>
      )}
      {f.type === "checkbox-single" && (
        <label className={"choice" + (value ? " is-checked" : "")}>
          <input type="checkbox" checked={!!value} onChange={e => set(f.name, e.target.checked)} />
          <div>
            <div className="choice__label">{f.label}{f.required && <span className="req"> *</span>}</div>
            {error && <div className="error-msg" style={{marginTop: 4}}>{error}</div>}
          </div>
        </label>
      )}
    </div>
  );
}

window.SarpahPages2 = { AudiencePage, ProductsIndex, FoodIndex, ComplianceIndex, CorridorsIndex, FormPage };
