/* ReportForm.jsx — public report flow, wired to /api/report */
const { useState } = React;

const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_FILES = 6;
const MEDIA_RE = /^(image|video)\//;
const MEDIA_EXT_RE = /\.(jpe?g|png|gif|mp4|mov|avi|webm)$/i;

function localDateTimeValue(d = new Date()) {
  const p = (n) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
}

function CategoryGrid({ selected, toggle, lang }) {
  return (
    <div className="cat-grid" role="group">
      {window.MELD.categories.map((c) => {
        const on = selected.includes(c.id);
        return (
          <button key={c.id} type="button" onClick={() => toggle(c.id)}
            aria-pressed={on}
            className={"cat-chip" + (on ? " on" : "")}>
            <span className="cat-ico"><Ico name={c.icon} size={22} /></span>
            <span className="cat-label">{c[lang]}</span>
            <span className="cat-check">{on ? <Ico name="check" size={14} /> : null}</span>
          </button>
        );
      })}
    </div>
  );
}

function WhenField({ when, setWhen, t }) {
  const isNow = when === "now";
  const maxDt = localDateTimeValue();
  return (
    <div>
      <div className="seg">
        <button type="button" className={"seg-btn" + (isNow ? " on" : "")} onClick={() => setWhen("now")}>
          <Ico name="clock" size={15} /> {t.when_now}
        </button>
        <button type="button" className={"seg-btn" + (!isNow ? " on" : "")}
          onClick={() => setWhen(when === "now" ? maxDt : when)}>
          <Ico name="calendar" size={15} /> {t.when_earlier}
        </button>
      </div>
      {!isNow && (
        <input id="incident-when" type="datetime-local" className="input" style={{ marginTop: 10 }}
          value={when} max={maxDt} onChange={(e) => setWhen(e.target.value)} />
      )}
    </div>
  );
}

function EvidenceField({ files, setFiles, t }) {
  const inputRef = React.useRef(null);
  const cameraRef = React.useRef(null);
  const [drag, setDrag] = useState(false);
  const [err, setErr] = useState("");

  function add(list) {
    const incoming = Array.from(list);
    const valid = [];
    for (const f of incoming) {
      // Mirror the server filter: a known media extension AND a media (or unknown/octet-stream) MIME.
      const mimeOk = MEDIA_RE.test(f.type) || !f.type || f.type === "application/octet-stream";
      const typeOk = MEDIA_EXT_RE.test(f.name) && mimeOk;
      if (!typeOk) { setErr(t.invalid_file); continue; }
      if (f.size > MAX_FILE_BYTES) { setErr(t.file_too_large); continue; }
      valid.push({ name: f.name, size: f.size, type: f.type, _file: f });
    }
    if (valid.length) { setErr(""); setFiles((prev) => [...prev, ...valid].slice(0, MAX_FILES)); }
  }

  return (
    <div>
      <div className={"dropzone" + (drag ? " drag" : "")}
        role="button" tabIndex={0}
        aria-label={t.drop_hint}
        onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); inputRef.current && inputRef.current.click(); } }}
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => { e.preventDefault(); setDrag(false); add(e.dataTransfer.files); }}
        onClick={() => inputRef.current && inputRef.current.click()}>
        <input ref={inputRef} type="file" accept="image/*,video/*" multiple hidden
          onChange={(e) => add(e.target.files)} />
        <input ref={cameraRef} type="file" accept="image/*" capture="environment" hidden
          onChange={(e) => add(e.target.files)} />
        <div className="dz-actions">
          <span className="dz-btn" role="button" tabIndex={0}
            onClick={(e) => { e.stopPropagation(); cameraRef.current && cameraRef.current.click(); }}
            onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.stopPropagation(); e.preventDefault(); cameraRef.current && cameraRef.current.click(); } }}>
            <Ico name="camera" size={18} /> {t.drop_photo}
          </span>
          <span className="dz-btn" role="button" tabIndex={0}
            onClick={(e) => { e.stopPropagation(); inputRef.current && inputRef.current.click(); }}
            onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.stopPropagation(); e.preventDefault(); inputRef.current && inputRef.current.click(); } }}>
            <Ico name="upload" size={18} /> {t.drop_upload}
          </span>
        </div>
        <div className="dz-hint">{t.drop_hint} · {t.drop_max}</div>
      </div>
      {err && <div className="err-line" style={{ marginTop: 8 }}><Ico name="circle-alert" size={15} /> {err}</div>}
      {files.length > 0 && (
        <div className="file-list">
          {files.map((f, i) => (
            <div key={i} className="file-pill">
              <Ico name={f.type && f.type.startsWith("video") ? "video" : "image"} size={15} />
              <span className="file-name">{f.name}</span>
              <span className="file-size">{fmtBytes(f.size)}</span>
              <button type="button" className="file-x" aria-label={t.remove_file}
                onClick={() => setFiles((p) => p.filter((_, j) => j !== i))}>
                <Ico name="x" size={13} />
              </button>
            </div>
          ))}
        </div>
      )}
      <div className="notice notice-warn" style={{ marginTop: 12 }}>
        <Ico name="eye-off" size={16} /> <span>{t.privacy_warn}</span>
      </div>
    </div>
  );
}

function ContactField({ contact, setContact, t }) {
  const c = contact;
  const set = (k, v) => setContact({ ...c, [k]: v });
  return (
    <div className="contact-split">
      <div className={"contact-left" + (c.anon ? " contact-left-dim" : "")}>
        <div>
          <label className="field-label" htmlFor="reporter-name">{t.name} {!c.anon && <span className="req">*</span>}</label>
          <input id="reporter-name" className="input" value={c.name} disabled={c.anon}
            onChange={(e) => set("name", e.target.value)} />
        </div>
        <div className="contact-row">
          <div>
            <label className="field-label" htmlFor="reporter-email">{t.email}</label>
            <input id="reporter-email" className="input" type="email" value={c.email} disabled={c.anon}
              onChange={(e) => set("email", e.target.value)} />
          </div>
          <div>
            <label className="field-label" htmlFor="reporter-phone">{t.phone}</label>
            <input id="reporter-phone" className="input" value={c.phone} disabled={c.anon}
              onChange={(e) => set("phone", e.target.value)} />
          </div>
        </div>
        {!c.anon && <p className="contact-hint">{t.contact_hint || (t.email + " " + (t.contact_oder || "oder") + " " + t.phone)}</p>}
      </div>
      <div className="contact-oder"><span>{t.contact_oder || "oder"}</span></div>
      <div className="contact-right">
        <label className="anon-toggle anon-toggle-v">
          <input type="checkbox" checked={c.anon} onChange={(e) => set("anon", e.target.checked)} />
          <span className="anon-box">{c.anon ? <Ico name="check" size={13} /> : null}</span>
          <span>{t.anon_ok}</span>
        </label>
      </div>
    </div>
  );
}

function ConsentField({ consent, setConsent, t }) {
  return (
    <label className="consent-row">
      <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
      <span className="anon-box">{consent ? <Ico name="check" size={13} /> : null}</span>
      <span className="consent-text">{t.consent_label}</span>
    </label>
  );
}

function MapField({ loc, setLoc, locErr, setLocErr, t, tall }) {
  const locateRef = React.useRef(null);
  const [busy, setBusy] = useState(false);
  const [serverAreas, setServerAreas] = useState(null);
  const [areasLoaded, setAreasLoaded] = useState(false);

  React.useEffect(() => {
    fetch("/api/areas")
      .then(r => r.json())
      .then(d => {
        const list = d.success && d.areas && d.areas.length ? d.areas : [];
        setServerAreas(list);
        setAreasLoaded(true);
      })
      .catch(() => { setServerAreas(null); setAreasLoaded(true); });
  }, []);

  // Re-validate a location picked before areas finished loading.
  React.useEffect(() => {
    if (!areasLoaded || !loc) return;
    const list = serverAreas || [];
    if (list.length && !findAreaForPoint(loc.lat, loc.lng, list)) {
      setLocErr(t.out_of_bounds);
      setLoc(null);
    }
  }, [areasLoaded, serverAreas]);

  function reverseGeocode(lat, lng) {
    setLoc((prev) => prev && prev.lat === lat && prev.lng === lng ? { ...prev, geocoding: true } : prev);
    fetch(`/api/geocode/reverse?lat=${lat}&lng=${lng}`)
      .then(r => r.json())
      .then(d => {
        if (!d.success) return;
        setLoc((prev) => prev && prev.lat === lat && prev.lng === lng
          ? { ...prev, place: d.place, geocoding: false } : prev);
      })
      .catch(() => setLoc((prev) => prev ? { ...prev, geocoding: false } : prev));
  }

  function applyLoc(ll) {
    setBusy(false);
    const list = serverAreas || [];
    if (list.length) {
      const area = findAreaForPoint(ll.lat, ll.lng, list);
      if (!area) {
        setLocErr(t.out_of_bounds);
        setLoc(null);
        return;
      }
      setLocErr(null);
      setLoc({ lat: ll.lat, lng: ll.lng, zone: area.name || null });
    } else {
      // No areas configured (or still loading) — server is the final gate.
      setLocErr(null);
      setLoc({ lat: ll.lat, lng: ll.lng, zone: null });
    }
    reverseGeocode(ll.lat, ll.lng);
  }

  const zoneName = zoneNameOf(loc);
  return (
    <div>
      <div className="map-wrap" style={{ height: tall ? 420 : 300 }}>
        <MapPicker mode="pick" center={window.MELD.center} mapStyle="satellite"
          value={loc} onChange={applyLoc} t={t} locateRef={locateRef}
          showGeofence={false}
          onLocateError={() => setBusy(false)}
          areas={serverAreas || []} />
        <button type="button" className="map-locate" onClick={() => { setBusy(true); locateRef.current && locateRef.current(); }}>
          <Ico name="locate-fixed" size={16} /> {busy ? t.locating : t.findloc}
        </button>
        {!loc && !locErr && <div className="map-tag">{t.map_hint}</div>}
      </div>
      {locErr && (
        <div className="notice notice-danger anim-up" style={{ marginTop: 10 }}>
          <Ico name="map-pin-x" size={16} /> <span>{locErr}</span>
        </div>
      )}
      {loc && (
        <div className="loc-readout anim-up">
          <Ico name="map-pin" size={16} />
          <div>
            <div className="loc-zone">{t.zone}: <strong>{zoneName || (loc.geocoding ? t.locating : "—")}</strong></div>
            <div className="loc-coords">{loc.lat.toFixed(5)}, {loc.lng.toFixed(5)}</div>
          </div>
        </div>
      )}
    </div>
  );
}

function SectionHead({ n, title, help }) {
  return (
    <div className="sec-head">
      {n != null && <span className="sec-num">{n}</span>}
      <div>
        <h3 className="sec-title">{title}</h3>
        {help && <p className="sec-help">{help}</p>}
      </div>
    </div>
  );
}

function SuccessView({ refId, t, onAgain }) {
  return (
    <div className="success anim-pop">
      <div className="success-mark"><Ico name="check" size={40} /></div>
      <h2 className="display success-title">{t.success_title}</h2>
      <p className="success-lead">{t.success_lead}</p>
      <div className="success-ref">{t.success_ref} <strong>{refId}</strong></div>
      <button className="btn btn-ghost" onClick={onAgain}><Ico name="rotate-ccw" size={16} /> {t.success_again}</button>
    </div>
  );
}

function ReportForm({ lang, t }) {
  const [cats, setCats] = useState([]);
  const [when, setWhen] = useState("now");
  const [desc, setDesc] = useState("");
  const [files, setFiles] = useState([]);
  const [loc, setLoc] = useState(null);
  const [locErr, setLocErr] = useState(null);
  const [contact, setContact] = useState({ name: "", email: "", phone: "", anon: false });
  const [consent, setConsent] = useState(false);
  const [done, setDone] = useState(null);
  const [err, setErr] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const toggleCat = (id) => setCats((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));

  function reset() {
    setCats([]); setWhen("now"); setDesc(""); setFiles([]); setLoc(null); setLocErr(null);
    setContact({ name: "", email: "", phone: "", anon: false }); setConsent(false);
    setDone(null); setErr(""); setSubmitting(false);
  }

  async function submit() {
    if (!cats.length) { setErr(t.required_what); return; }
    if (!loc) { setErr(t.required_where); return; }
    if (!contact.anon) {
      if (!contact.name) { setErr(t.required_name); return; }
      if (!contact.email && !contact.phone) { setErr(t.required_contact); return; }
    }
    if (!consent) { setErr(t.consent_required); return; }

    setErr("");
    setSubmitting(true);

    const fd = new FormData();
    fd.append("latitude", String(loc.lat));
    fd.append("longitude", String(loc.lng));

    const catLabels = cats.map((id) => catById(id)[lang]).join(", ");
    const fullDesc = cats.length ? `[${catLabels}]\n${desc}`.trim() : desc;
    fd.append("description", fullDesc);
    fd.append("categories", JSON.stringify(cats));

    // Always send an incident time: "now" is materialised at submission time so
    // the admin view never has to guess from the (UTC) created_at fallback.
    fd.append("incident-date-time", when === "now" ? localDateTimeValue() : when);
    fd.append("tz-offset", String(-Math.round(new Date().getTimezoneOffset() / 60)));
    fd.append("consent", "1");

    if (!contact.anon) {
      if (contact.name) fd.append("reporter-name", contact.name);
      if (contact.email) fd.append("reporter-email", contact.email);
      if (contact.phone) fd.append("reporter-phone", contact.phone);
    }

    files.forEach((f) => { if (f._file) fd.append("file", f._file); });

    try {
      const resp = await fetch("/api/report", { method: "POST", body: fd });
      const text = await resp.text();
      let data = {};
      try { data = text ? JSON.parse(text) : {}; } catch (e) { data = {}; }
      if (resp.ok && data.success) {
        setDone(genRef(data.id));
      } else {
        let msg = data.error || t.submit_error;
        if (/outside allowed reporting areas/i.test(msg)) msg = t.out_of_bounds;
        else if (/consent/i.test(msg)) msg = t.consent_required;
        else if (/too large/i.test(msg)) msg = t.file_too_large;
        setErr(msg);
        setSubmitting(false);
      }
    } catch (e) {
      setErr(t.submit_error);
      setSubmitting(false);
    }
  }

  if (done) return <div className="form-shell"><SuccessView refId={done} t={t} onAgain={reset} /></div>;

  const ctx = { cats, toggleCat, when, setWhen, desc, setDesc, files, setFiles, loc, setLoc, locErr, setLocErr, contact, setContact, consent, setConsent, lang, t, submitting };

  return <SteppedForm {...ctx} submit={submit} err={err} setErr={setErr} />;
}

window.ReportForm = ReportForm;
window.CategoryGrid = CategoryGrid;
window.WhenField = WhenField;
window.EvidenceField = EvidenceField;
window.ContactField = ContactField;
window.ConsentField = ConsentField;
window.MapField = MapField;
window.SectionHead = SectionHead;
