/* global React, CONTACT */

/* ============================================================================
   Egan Stone — Memorials (customer facing)

   WHY THERE IS NO LIVE INSCRIPTION PREVIEW HERE ANY MORE
   There used to be one: you typed the wording and it was drawn onto the actual
   photograph of the stone. It measured well and it fitted properly, but it never
   looked like cut granite — lettering catches light along every incised edge and
   flat type on a photo does not. Showing a family a mock-up of their mother's
   headstone that looks *nearly* right is worse than showing none at all, so it
   was taken out rather than polished. Wording is agreed on a real proof before
   anything is cut, which is where it belongs.

   What the website does now is the honest job: show the range, take a plain
   enquiry, and get the details on the phone or in the yard.
   ========================================================================== */

/* Roughly how far the vans go for memorial work. Soft, not a wall — an enquiry
   from just outside still comes through and the office decides. */
const RADIUS_KM = 55;

const SECTIONS = [
  { key: "headstones",  label: "New headstones" },
  { key: "renovation",  label: "Renovation & cleaning" },
  { key: "accessories", label: "Accessories" },
];
const SECTION_KEYS = SECTIONS.map(s => s.key);

/* What a renovation enquiry might be. Ticking is easier than describing, and it
   tells the workshop which trade the job actually belongs to. */
const RENOVATION_WORK = [
  "Cleaning", "Additional inscription", "Re-lettering", "Re-gilding",
  "Kerbing", "Chippings", "Repair or re-fix", "Not sure — please advise",
];

const MAX_PHOTO_MB = 4;

function Memorials({ navigate, code }) {
  const [designs, setDesigns] = React.useState(null);
  const [loadErr, setLoadErr] = React.useState("");

  /* The URL decides what you're looking at, so every one of these is a link a
     family can be sent: #/memorials, #/memorials/renovation, #/memorials/M02. */
  const section = SECTION_KEYS.indexOf(String(code || "").toLowerCase()) !== -1
    ? String(code).toLowerCase() : "headstones";
  const chosen = React.useMemo(
    () => (code && designs ? designs.find(d => d.code === code) || null : null),
    [code, designs]
  );

  const [form, setForm] = React.useState({ name: "", phone: "", email: "", message: "", website: "" });
  const [work, setWork] = React.useState([]);
  const [location, setLocation] = React.useState("");
  const [photo, setPhoto] = React.useState(null);          // { data, name, size }
  const [photoErr, setPhotoErr] = React.useState("");
  const [sending, setSending] = React.useState(false);
  // State is not synchronous, so three fast clicks all read sending===false and
  // all three send. A ref latches immediately.
  const inFlight = React.useRef(false);
  const [sent, setSent] = React.useState(false);
  const [formErr, setFormErr] = React.useState("");

  React.useEffect(() => {
    let alive = true;
    fetch("/api/memorial-range")
      .then(r => r.json())
      .then(d => {
        if (!alive) return;
        if (d.ok && d.designs) setDesigns(d.designs);
        else setLoadErr("We couldn't load the range just now.");
      })
      .catch(() => { if (alive) setLoadErr("We couldn't load the range just now."); });
    return () => { alive = false; };
  }, []);

  /* Moving between sections or stones starts a fresh enquiry. Everything that
     describes the JOB is cleared — otherwise ticking "Cleaning, Re-lettering"
     on the renovation form and then wandering over to Accessories sends us an
     enquiry for a plaque that also asks for a headstone to be re-lettered.
     Name, phone and email stay: it is still the same person. */
  React.useEffect(() => {
    setSent(false); setFormErr(""); setPhotoErr("");
    setWork([]); setLocation(""); setPhoto(null);
    setForm(f => ({ ...f, message: "" }));
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [code]);

  const setF = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleWork = w =>
    setWork(list => (list.indexOf(w) === -1 ? list.concat(w) : list.filter(x => x !== w)));

  const readPhoto = file => {
    setPhotoErr("");
    if (!file) { setPhoto(null); return; }
    if (!/^image\//.test(file.type)) { setPhoto(null); setPhotoErr("That needs to be a photo — a JPG or a PNG."); return; }
    if (file.size > MAX_PHOTO_MB * 1024 * 1024) {
      setPhoto(null);
      setPhotoErr(`That photo is over ${MAX_PHOTO_MB}MB. Most phones let you send a smaller one.`);
      return;
    }
    const reader = new FileReader();
    reader.onload = () => setPhoto({ data: String(reader.result || ""), name: file.name, size: file.size });
    reader.onerror = () => setPhotoErr("We couldn't read that photo. Try another one.");
    reader.readAsDataURL(file);
  };

  const contactOk = form.phone.trim() || form.email.trim();

  const jobType = chosen ? "New headstone"
    : section === "renovation" ? "Renovation"
    : section === "accessories" ? "Accessories" : "New headstone";

  const submit = e => {
    e.preventDefault();
    if (inFlight.current) return;
    if (!form.name.trim()) { setFormErr("Please tell us your name."); return; }
    if (!contactOk) { setFormErr("Please give us a phone number or an email address so we can reply."); return; }
    inFlight.current = true;
    setSending(true); setFormErr("");
    fetch("/api/memorial-range", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: form.name, phone: form.phone, email: form.email,
        message: form.message, website: form.website,
        jobType,
        design: chosen ? chosen.code : "",
        material: chosen ? chosen.material : "",
        // Renovation is the only form that asks these, so it is the only one
        // that sends them.
        work: jobType === "Renovation" ? work : [],
        location: jobType === "Renovation" ? location : "",
        photoData: jobType === "Renovation" && photo ? photo.data : "",
        photoName: jobType === "Renovation" && photo ? photo.name : "",
      }),
    })
      .then(r => r.json().then(d => ({ ok: r.ok, d })))
      .then(({ ok, d }) => {
        inFlight.current = false;
        setSending(false);
        if (ok && d && d.ok) { setSent(true); return; }
        setFormErr((d && d.error) || "Something went wrong our end. Please ring us instead.");
      })
      .catch(() => {
        inFlight.current = false;
        setSending(false);
        setFormErr("We couldn't send that. Please check your connection, or ring us.");
      });
  };

  /* ---------------------------------------------------------------- pieces */
  const radiusNote = (
    <p className="mem-radius">
      We look after memorials within roughly <strong>{RADIUS_KM}km of Kilbeggan</strong>.
      If you're a bit outside that, send it anyway and we'll tell you straight.
    </p>
  );

  const contactFields = (
    <div className="mem-fields">
      <div className="mem-field">
        <label className="mem-label" htmlFor="mem-name">Your name</label>
        <input id="mem-name" className="mem-input" value={form.name}
               onChange={e => setF("name", e.target.value)} autoComplete="name" />
      </div>
      <div className="mem-field">
        <label className="mem-label" htmlFor="mem-phone">Phone</label>
        <input id="mem-phone" className="mem-input" value={form.phone} inputMode="tel"
               onChange={e => setF("phone", e.target.value)} autoComplete="tel" />
      </div>
      <div className="mem-field">
        <label className="mem-label" htmlFor="mem-email">Email</label>
        <input id="mem-email" className="mem-input" type="email" value={form.email}
               onChange={e => setF("email", e.target.value)} autoComplete="email" />
      </div>
    </div>
  );

  /* A hidden field no person ever fills in. Bots do. */
  const honeypot = (
    <div className="mem-hp" aria-hidden="true">
      <label htmlFor="mem-website">Website</label>
      <input id="mem-website" tabIndex={-1} autoComplete="off" value={form.website}
             onChange={e => setF("website", e.target.value)} />
    </div>
  );

  const thanks = what => (
    <div className="mem-sent" role="status">
      <strong>Thank you — we have your enquiry.</strong>
      <p>{what}</p>
      <p>
        If you'd rather talk now, ring us on <a href={CONTACT.phoneHref}>{CONTACT.phoneDisplay}</a>.
      </p>
    </div>
  );

  const sendButton = label => (
    <React.Fragment>
      {formErr ? <p className="mem-formerr" role="alert">{formErr}</p> : null}
      <button type="submit" className="mem-send" disabled={sending}>
        {sending ? "Sending…" : label}
      </button>
      <p className="mem-privacy">
        We use these details only to come back to you about this enquiry.{" "}
        <a href="#/privacy" onClick={e => { e.preventDefault(); navigate("privacy"); }}>How we handle your information</a>.
      </p>
    </React.Fragment>
  );

  /* ------------------------------------------------------- one stone's page */
  if (chosen) {
    return (
      <section className="mem-detail">
        <div className="container">
          <button type="button" className="mem-back" onClick={() => navigate("memorials")}>
            ← All memorials
          </button>

          <header className="mem-head">
            <div className="kicker" style={{ color: "var(--teal-text)" }}>{chosen.code} · {chosen.material}</div>
            <h1 className="mem-title">{chosen.name}</h1>
            <div className="mem-avail">
              {chosen.inStock
                ? <span className="mem-in">In our yard now — about {chosen.weeks} weeks to letter and fit</span>
                : <span className="mem-out">Made to order{chosen.weeks ? ` — about ${chosen.weeks} weeks` : ""}</span>}
              {chosen.price ? <span className="mem-price">from €{chosen.price.toLocaleString("en-IE")}</span> : null}
            </div>
          </header>

          <div className="mem-cols">
            <div className="mem-shot">
              <img src={chosen.photo} alt={`${chosen.name} in ${chosen.material}`} loading="lazy" />
              <p className="mem-note">
                Shown with sample lettering. Your own wording is set out on a proof
                and agreed with you before anything is cut.
              </p>
            </div>

            <div className="mem-editcol">
              <h2 className="mem-h2">Enquire about this memorial</h2>
              <p className="mem-help">
                Tell us how to reach you and we'll go through the stone, the lettering
                and your cemetery's own requirements. There's nothing to decide now.
              </p>
              {radiusNote}

              {sent ? thanks(
                `We have your enquiry about ${chosen.code}. Someone from the workshop will be in
                 touch to go through the stone and the wording. Nothing is cut until you have seen
                 and approved a proof.`
              ) : (
                <form className="mem-form" onSubmit={submit} noValidate>
                  {contactFields}
                  <div className="mem-field">
                    <label className="mem-label" htmlFor="mem-msg">Anything you'd like us to know</label>
                    <textarea id="mem-msg" className="mem-input mem-msg" rows={4} value={form.message}
                              onChange={e => setF("message", e.target.value)}
                              placeholder="The cemetery, whether there's an existing grave or kerbing, roughly when you'd like it — whatever you know." />
                  </div>
                  {honeypot}
                  {sendButton("Send my enquiry")}
                </form>
              )}
            </div>
          </div>
        </div>
      </section>
    );
  }

  /* ----------------------------------------------------------- the sections */
  const tabs = (
    <nav className="mem-tabs" aria-label="Memorial services">
      {SECTIONS.map(s => (
        <button
          key={s.key} type="button"
          className={"mem-tab" + (section === s.key ? " on" : "")}
          aria-current={section === s.key ? "page" : undefined}
          onClick={() => navigate(s.key === "headstones" ? "memorials" : "memorials/" + s.key)}
        >{s.label}</button>
      ))}
    </nav>
  );

  const headstones = (
    <React.Fragment>
      <p className="mem-intro">
        Every stone below is one we make. Tap one to see it properly and send an enquiry —
        we'll go through the wording, the finish and the cemetery's requirements with you.
      </p>
      {radiusNote}
      {loadErr ? <div className="mem-err">{loadErr} Ring us on <a href={CONTACT.phoneHref}>{CONTACT.phoneDisplay}</a>.</div> : null}
      {!designs && !loadErr ? <p className="mem-loading">Loading the range…</p> : null}
      {designs ? (
        <div className="mem-grid">
          {designs.map(d => (
            <button key={d.code} type="button" className="mem-card"
                    onClick={() => navigate("memorials/" + d.code)}>
              <div className="mem-cardimg">
                <img src={d.photo} alt={`${d.name} in ${d.material}`} loading="lazy" />
                {d.inStock ? <span className="mem-badge">In the yard</span> : null}
              </div>
              <div className="mem-cardbody">
                <div className="mem-cardname">{d.name}</div>
                <div className="mem-cardmat">{d.material}</div>
                <div className="mem-cardcta">See this stone →</div>
              </div>
            </button>
          ))}
        </div>
      ) : null}
    </React.Fragment>
  );

  const renovation = (
    <div className="mem-single">
      <p className="mem-intro">
        Cleaning, added inscriptions, re-lettering, kerbing and chippings on a stone
        that's already standing. Tell us what you're after and where the grave is.
      </p>
      {radiusNote}

      {sent ? thanks(
        `We have your enquiry. We'll come back to you about the work and, if we need to,
         call out to see the grave before pricing it.`
      ) : (
        <form className="mem-form" onSubmit={submit} noValidate>
          <fieldset className="mem-fieldset">
            <legend className="mem-label">What do you need? Tick anything that applies</legend>
            <div className="mem-work">
              {RENOVATION_WORK.map(w => (
                <label key={w} className={"mem-workitem" + (work.indexOf(w) !== -1 ? " on" : "")}>
                  <input type="checkbox" checked={work.indexOf(w) !== -1} onChange={() => toggleWork(w)} />
                  {w}
                </label>
              ))}
            </div>
          </fieldset>

          <div className="mem-field">
            <label className="mem-label" htmlFor="mem-loc">Where is the grave?</label>
            <textarea id="mem-loc" className="mem-input mem-msg" rows={3} value={location}
                      onChange={e => setLocation(e.target.value)}
                      placeholder="The cemetery, and how we'd find the grave — section, row, plot number, or the names on the stone." />
            <p className="mem-hint">Old graveyards are hard to search. The more you can tell us, the less chance of a wasted trip.</p>
          </div>

          <div className="mem-field">
            <label className="mem-label" htmlFor="mem-photo">A photo of the grave</label>
            <input id="mem-photo" className="mem-file" type="file" accept="image/*"
                   onChange={e => readPhoto(e.target.files && e.target.files[0])} />
            <p className="mem-hint">
              <strong>This one really matters.</strong> We can't price cleaning or re-lettering
              accurately without seeing the state of the existing stone — and it shows us how to
              find it. A photo on your phone is grand.
            </p>
            {photo ? <p className="mem-fileok">Attached: {photo.name}</p> : null}
            {photoErr ? <p className="mem-formerr">{photoErr}</p> : null}
          </div>

          {contactFields}
          <div className="mem-field">
            <label className="mem-label" htmlFor="mem-msg">Anything else</label>
            <textarea id="mem-msg" className="mem-input mem-msg" rows={3} value={form.message}
                      onChange={e => setF("message", e.target.value)} />
          </div>
          {honeypot}
          {sendButton("Send my enquiry")}
        </form>
      )}
    </div>
  );

  const accessories = (
    <div className="mem-single">
      <p className="mem-intro">
        Small plaques for a grave or a memorial — cut and lettered in the workshop here.
        Tell us roughly what you have in mind and we'll come back with sizes and prices.
      </p>
      {radiusNote}

      {sent ? thanks("We have your enquiry and we'll come back to you with sizes and prices.") : (
        <form className="mem-form" onSubmit={submit} noValidate>
          {contactFields}
          <div className="mem-field">
            <label className="mem-label" htmlFor="mem-msg">What are you looking for?</label>
            <textarea id="mem-msg" className="mem-input mem-msg" rows={4} value={form.message}
                      onChange={e => setF("message", e.target.value)}
                      placeholder="What you'd like, roughly what size, and the wording if you know it. The cemetery too, if it's going on a grave." />
          </div>
          {honeypot}
          {sendButton("Send my enquiry")}
        </form>
      )}
    </div>
  );

  return (
    <React.Fragment>
      <section className="mem-hero">
        <div className="container">
          <div className="kicker" style={{ color: "#7CC3D8", marginBottom: 20 }}>Memorials</div>
          <h1 className="display" style={{ color: "white", maxWidth: 900 }}>
            Headstones cut and lettered<br /><em className="pull" style={{ color: "#7CC3D8" }}>in Kilbeggan.</em>
          </h1>
          <p className="lede" style={{ color: "rgba(255,255,255,0.78)", maxWidth: 620, marginTop: 24, fontSize: 17 }}>
            Six generations of stone. New headstones, work on stones already standing,
            and small plaques — all made here, not bought in.
          </p>
        </div>
      </section>

      <section className="section">
        <div className="container">
          {tabs}
          {section === "renovation" ? renovation
            : section === "accessories" ? accessories
            : headstones}
        </div>
      </section>
    </React.Fragment>
  );
}
