// Main site sections — all copy comes from the Tweaks panel so it
// survives refresh and can be edited live.

const { useState, useEffect, useRef } = React;

// Turn a string with blank-line separated paragraphs into <p> blocks,
// running each through renderRich for *italic* support.
function paragraphs(text, className) {
  if (!text) return null;
  return String(text)
    .split(/\n{2,}/)
    .map((block, i) => (
      <p key={i} className={className}>
        {renderRich(block.replace(/\n/g, " "))}
      </p>
    ));
}

function normalizePublicListing(listing) {
  const status = listing.status || "new";
  const statusClass = ["verkocht", "verkocht_ov", "sold"].includes(status)
    ? "sold"
    : ["bezichtiging", "open"].includes(status)
      ? "open"
      : "new";
  const photos = Array.isArray(listing.fotos)
    ? listing.fotos
    : Array.isArray(listing.photos)
      ? listing.photos
      : [];

  return {
    id: listing.id,
    title: listing.titel || listing.title || "Woning",
    location: [listing.adres, listing.plaats || listing.location]
      .filter(Boolean)
      .join(" - "),
    price: listing.prijsLabel || listing.price || "",
    statusClass,
    statusLabel:
      listing.statusLabel ||
      {
        nieuw: "Nieuw in verkoop",
        bezichtiging: "Bezichtiging",
        verkocht: "Verkocht",
        verkocht_ov: "Verkocht o.v.",
        new: "Nieuw in verkoop",
        open: "Bezichtiging",
        sold: "Verkocht",
      }[status] ||
      "Nieuw in verkoop",
    beds: listing.slaapkamers ?? listing.beds ?? 0,
    baths: listing.badkamers ?? listing.baths ?? 0,
    area: listing.woonoppervlak ?? listing.area ?? 0,
    tone: listing.kleurToon || listing.tone || "warm",
    image: photos[0] || listing.image || "",
  };
}

// --- HEADER ------------------------------------------------------------
const Header = ({ onNavigate, t }) => {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [menuOpen]);
  const go = (e, id) => {
    e.preventDefault();
    setMenuOpen(false);
    onNavigate(id);
  };
  return (
    <header
      className={`site-header ${scrolled ? "is-scrolled" : ""} ${menuOpen ? "menu-open" : ""}`}
    >
      <a href="#top" className="brand" onClick={(e) => go(e, "top")}>
        {t.brandTitle}
        {t.brandSub && <small>{t.brandSub}</small>}
      </a>
      <nav className="main-nav" aria-label="Hoofdnavigatie">
        <a href="#diensten" onClick={(e) => go(e, "diensten")}>
          {t.navLabel1}
        </a>
        <a href="#werkwijze" onClick={(e) => go(e, "werkwijze")}>
          {t.navLabel2}
        </a>
        <a href="#contact" onClick={(e) => go(e, "contact")}>
          {t.navLabel3}
        </a>
      </nav>
      <a
        href="#aanbod"
        className="cta header-cta"
        onClick={(e) => go(e, "aanbod")}
      >
        {t.navCtaLabel}
      </a>
      <button
        type="button"
        className="nav-toggle"
        aria-label={menuOpen ? "Menu sluiten" : "Menu openen"}
        aria-expanded={menuOpen}
        onClick={() => setMenuOpen((o) => !o)}
      >
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
      </button>
    </header>
  );
};

// --- HERO --------------------------------------------------------------
const Hero = ({ onNavigate, tweaks = {} }) => {
  const t = tweaks;
  return (
    <section className="hero-shell" id="top" data-screen-label="01 Hero">
      <Header onNavigate={onNavigate} t={t} />
      <div className="hero-stage">
        <img
          className="hero-portrait"
          src="./assets/rogier-portrait.png"
          alt="Rogier Zwarthoff"
        />
        <div className="hero-copy hero">
          <h1>{renderRich(t.heroTitle)}</h1>
          <div className="hero-lede-wrap">
            {paragraphs(t.heroLede, "hero-lede")}
          </div>
          <div className="hero-actions">
            <a
              href="#contact"
              className="cta cta-primary"
              onClick={(e) => {
                e.preventDefault();
                onNavigate("contact");
              }}
            >
              Plan een kennismaking <Ico name="arrow" />
            </a>
            <a
              href="#aanbod"
              className="hero-link"
              onClick={(e) => {
                e.preventDefault();
                onNavigate("aanbod");
              }}
            >
              Bekijk aanbod <span aria-hidden="true">→</span>
            </a>
          </div>
          {t.showSign !== false && (t.heroSignName || t.heroSignMeta) && (
            <div className="hero-sign">
              {t.heroSignName && <span className="sig">{t.heroSignName}</span>}
              {t.heroSignMeta && <span>{t.heroSignMeta}</span>}
            </div>
          )}
        </div>
        {t.showScroll !== false && t.heroScrollLbl && (
          <div className="scroll-hint" aria-hidden="true">
            <span>{t.heroScrollLbl}</span>
            <span className="line"></span>
          </div>
        )}
      </div>
    </section>
  );
};

// --- LISTINGS ----------------------------------------------------------
const Listings = ({ t }) => {
  const visible = (window.LISTINGS_FROM_SERVER || window.LISTINGS || [])
    .filter((listing) => listing.zichtbaar !== false)
    .sort((a, b) => (a.volgorde || 0) - (b.volgorde || 0))
    .map(normalizePublicListing);
  return (
    <section
      className="page-section listings"
      id="aanbod"
      data-screen-label="02 Aanbod"
    >
      <div className="section-header">
        <div>
          <span className="eyebrow">{t.aanbodEyebrow}</span>
          <h2>{renderRich(t.aanbodTitle)}</h2>
        </div>
        <div className="intro-col">
          {paragraphs(t.aanbodIntro, "intro")}
          <a
            href="#contact"
            className="cta cta-light"
            onClick={(e) => {
              e.preventDefault();
              document
                .getElementById("contact")
                .scrollIntoView({ behavior: "smooth" });
            }}
          >
            {t.aanbodCta} <Ico name="arrow" />
          </a>
        </div>
      </div>

      <div className="listing-grid">
        {visible.map((l) => (
          <article key={l.id} className="listing-card">
            <div className="listing-image">
              {l.image ? (
                <img
                  src={l.image}
                  alt={l.title}
                  style={{
                    position: "absolute",
                    inset: 0,
                    width: "100%",
                    height: "100%",
                    objectFit: "cover",
                  }}
                />
              ) : (
                <ListingArt tone={l.tone} sold={l.statusClass === "sold"} />
              )}
              <span className={`listing-status status-${l.statusClass}`}>
                {l.statusLabel}
              </span>
            </div>
            <div className="listing-body">
              <p className="loc">{l.location}</p>
              <h3>{l.title}</h3>
              <p className="price">{l.price}</p>
              <div className="specs">
                <span>
                  <Ico name="bed" /> {l.beds} slaapk.
                </span>
                <span>
                  <Ico name="bath" /> {l.baths} badk.
                </span>
                <span>
                  <Ico name="area" /> {l.area} m²
                </span>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
};

// --- SERVICES ----------------------------------------------------------
const Services = ({ t }) => (
  <section
    className="page-section services-section"
    id="diensten"
    data-screen-label="03 Diensten"
  >
    <div className="section-header">
      <div>
        <span className="eyebrow">{t.dienstenEyebrow}</span>
        <h2>{renderRich(t.dienstenTitle)}</h2>
      </div>
      <div className="intro-col">{paragraphs(t.dienstenIntro, "intro")}</div>
    </div>

    <div className="services-grid">
      {window.SERVICES.map((s) => (
        <article key={s.num} className="service">
          <span className="num">{s.num}</span>
          <div>
            <h3>{s.title}</h3>
            <p>{s.body}</p>
            <ul>
              {s.tags.map((tag) => (
                <li key={tag}>{tag}</li>
              ))}
            </ul>
          </div>
        </article>
      ))}
    </div>
  </section>
);

// --- PROCESS -----------------------------------------------------------
const Process = ({ t }) => (
  <section
    className="page-section process-section"
    id="werkwijze"
    data-screen-label="04 Werkwijze"
  >
    <div className="section-header">
      <div>
        <span className="eyebrow">{t.werkwijzeEyebrow}</span>
        <h2>{renderRich(t.werkwijzeTitle)}</h2>
      </div>
      <div className="intro-col">{paragraphs(t.werkwijzeIntro, "intro")}</div>
    </div>

    <div className="process-steps">
      {window.PROCESS.map((s) => (
        <div key={s.num} className="step">
          <span className="dot">{s.num}</span>
          <h3>{s.title}</h3>
          <p>{s.body}</p>
        </div>
      ))}
    </div>
  </section>
);

// --- DOCUMENTS ---------------------------------------------------------
const DocIcon = ({ type }) => {
  // Minimal file icons — clean line style
  if (type === "pdf") {
    return (
      <svg viewBox="0 0 40 48" width="40" height="48" aria-hidden="true">
        <path
          d="M6 2h20l8 8v34a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
        />
        <path
          d="M26 2v8h8"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
        />
        <text
          x="20"
          y="34"
          fontFamily="ui-sans-serif, system-ui"
          fontSize="8"
          fontWeight="700"
          textAnchor="middle"
          fill="currentColor"
          letterSpacing="0.5"
        >
          PDF
        </text>
      </svg>
    );
  }
  if (type === "doc") {
    return (
      <svg viewBox="0 0 40 48" width="40" height="48" aria-hidden="true">
        <path
          d="M6 2h20l8 8v34a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
        />
        <path
          d="M26 2v8h8"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
        />
        <text
          x="20"
          y="34"
          fontFamily="ui-sans-serif, system-ui"
          fontSize="8"
          fontWeight="700"
          textAnchor="middle"
          fill="currentColor"
          letterSpacing="0.5"
        >
          DOC
        </text>
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 40 48" width="40" height="48" aria-hidden="true">
      <path
        d="M6 2h20l8 8v34a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
      />
      <path d="M26 2v8h8" fill="none" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  );
};

const Documents = ({ t }) => {
  // Build doc list from tweaks (up to 6 documents)
  const docs = [];
  for (let i = 1; i <= 6; i++) {
    const title = t[`doc${i}Title`];
    if (!title) continue;
    docs.push({
      title,
      desc: t[`doc${i}Desc`] || "",
      type: t[`doc${i}Type`] || "pdf",
      meta: t[`doc${i}Meta`] || "",
      href: t[`doc${i}Href`] || "#",
    });
  }
  if (docs.length === 0) return null;

  return (
    <section
      className="page-section documents-section"
      id="documenten"
      data-screen-label="06 Documenten"
    >
      <div className="section-header">
        <div>
          <span className="eyebrow">{t.docsEyebrow}</span>
          <h2>{renderRich(t.docsTitle)}</h2>
        </div>
        <div className="intro-col">{paragraphs(t.docsIntro, "intro")}</div>
      </div>

      <div className="docs-grid">
        {docs.map((d, i) => (
          <a
            key={i}
            href={d.href}
            className="doc-card"
            target="_blank"
            rel="noopener"
            download
          >
            <div className="doc-icon">
              <DocIcon type={d.type} />
            </div>
            <div className="doc-body">
              <h3>{d.title}</h3>
              {d.desc && <p>{d.desc}</p>}
              <div className="doc-meta">
                <span className="doc-type">{d.type.toUpperCase()}</span>
                {d.meta && (
                  <>
                    <span className="dot-sep">·</span>
                    <span>{d.meta}</span>
                  </>
                )}
              </div>
            </div>
            <div className="doc-action" aria-hidden="true">
              <svg
                viewBox="0 0 24 24"
                width="20"
                height="20"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <path d="M12 3v13M6 11l6 6 6-6M4 21h16" />
              </svg>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
};

// --- CONTACT -----------------------------------------------------------
const Contact = ({ t }) => {
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    intent: "Verkoop",
    message: "",
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const intents = ["Verkoop", "Aankoop", "Taxatie", "Hypotheek", "Iets anders"];

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Vul uw naam in.";
    if (!form.email.trim()) e.email = "Vul uw e-mailadres in.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
      e.email = "Dit e-mailadres klopt niet.";
    if (!form.message.trim() || form.message.trim().length < 8)
      e.message = "Schrijf kort waar u aan denkt.";
    return e;
  };

  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) {
      setSubmitted(true);
      fetch("/admin/api.php?action=inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      }).catch(() => {});
    }
  };

  const set = (k) => (ev) => {
    setForm((f) => ({ ...f, [k]: ev.target.value }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: undefined }));
  };

  return (
    <section
      className="page-section contact-section"
      id="contact"
      data-screen-label="05 Contact"
    >
      <div className="contact-grid">
        <aside className="contact-aside">
          <span className="eyebrow">{t.contactEyebrow}</span>
          <h2>{renderRich(t.contactTitle)}</h2>
          {paragraphs(t.contactIntro)}
          <div className="contact-details">
            {t.contactPhone && (
              <div className="row">
                <div>
                  <div className="label">Telefoon</div>
                  <a
                    className="nowrap"
                    href={`tel:${t.contactPhone.replace(/[^+\d]/g, "")}`}
                  >
                    {t.contactPhone}
                  </a>
                </div>
              </div>
            )}
            {t.contactEmail && (
              <div className="row">
                <div>
                  <div className="label">E-mail</div>
                  <a className="nowrap" href={`mailto:${t.contactEmail}`}>
                    {t.contactEmail}
                  </a>
                </div>
              </div>
            )}
            {t.contactResponse && (
              <div className="response-pledge">
                <span className="pledge-dot" aria-hidden="true"></span>
                <span>{t.contactResponse}</span>
              </div>
            )}
          </div>
        </aside>

        {submitted ? (
          <div className="success">
            <div className="checkmark">✓</div>
            <h3>Bedankt, {form.name.split(" ")[0]}.</h3>
            <p>
              Uw bericht is binnen. Ik neem uiterlijk de volgende werkdag
              persoonlijk contact met u op. Tot snel!
            </p>
          </div>
        ) : (
          <form className="contact-form" onSubmit={submit} noValidate>
            <div className="field">
              <label>Ik heb interesse in</label>
              <div className="chips">
                {intents.map((i) => (
                  <button
                    type="button"
                    key={i}
                    className={form.intent === i ? "active" : ""}
                    onClick={() => setForm((f) => ({ ...f, intent: i }))}
                  >
                    {i}
                  </button>
                ))}
              </div>
            </div>

            <div className="row-2">
              <div className={`field ${errors.name ? "has-error" : ""}`}>
                <label htmlFor="cf-name">Naam</label>
                <input
                  id="cf-name"
                  type="text"
                  value={form.name}
                  onChange={set("name")}
                  autoComplete="name"
                />
                {errors.name && (
                  <span className="error-msg">{errors.name}</span>
                )}
              </div>
              <div className={`field ${errors.email ? "has-error" : ""}`}>
                <label htmlFor="cf-email">E-mail</label>
                <input
                  id="cf-email"
                  type="email"
                  value={form.email}
                  onChange={set("email")}
                  autoComplete="email"
                />
                {errors.email && (
                  <span className="error-msg">{errors.email}</span>
                )}
              </div>
            </div>

            <div className="field">
              <label htmlFor="cf-phone">
                Telefoon{" "}
                <span
                  style={{ opacity: 0.55, fontWeight: 400, letterSpacing: 0 }}
                >
                  (optioneel)
                </span>
              </label>
              <input
                id="cf-phone"
                type="tel"
                value={form.phone}
                onChange={set("phone")}
                autoComplete="tel"
              />
            </div>

            <div className={`field ${errors.message ? "has-error" : ""}`}>
              <label htmlFor="cf-msg">Vertel kort waar u aan denkt</label>
              <textarea
                id="cf-msg"
                rows="4"
                value={form.message}
                onChange={set("message")}
              />
              {errors.message && (
                <span className="error-msg">{errors.message}</span>
              )}
            </div>

            <div className="form-footer">
              <span className="disclaimer">
                Door te verzenden gaat u akkoord met een persoonlijke reactie
                per e-mail of telefoon.
              </span>
              <button type="submit" className="cta">
                Verstuur bericht <Ico name="arrow" />
              </button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
};

// --- FOOTER ------------------------------------------------------------
const Footer = ({ t }) => {
  const year = new Date().getFullYear();
  return (
    <footer className="site-footer">
      <div className="footer-inner">
        <div className="footer-brand-col">
          <span className="footer-brand">{t.brandTitle}</span>
          <p>Is een handelsnaam van:</p>
          <p className="footer-entity">
            <strong>Uw Paleis B.V.</strong>
            <br />
            <span className="nowrap">KvK: 74025805</span>
          </p>
          <p className="footer-entity">
            In samenwerking met Uw Hypotheek:
            <br />
            <strong>Uw Zekerheid B.V.</strong>
            <br />
            <span className="nowrap">KvK: 32158765</span> &middot;{" "}
            <span className="nowrap">AFM: 12020092</span>
          </p>
        </div>
        <div>
          <h4>Contact</h4>
          {t.contactPhone && (
            <a
              className="nowrap"
              href={`tel:${t.contactPhone.replace(/[^+\d]/g, "")}`}
            >
              {t.contactPhone}
            </a>
          )}
          {t.contactEmail && (
            <a className="nowrap" href={`mailto:${t.contactEmail}`}>
              {t.contactEmail}
            </a>
          )}
        </div>
        <div>
          <h4>Aangesloten bij</h4>
          <p style={{ margin: 0 }}>Vastgoed Nederland &middot; MMCEPI</p>
          <p style={{ margin: 0 }}>SCVM &middot; NRVT &middot; Hypokeur</p>
        </div>
      </div>
      <div className="footer-copy">
        <span>
          © {year} {t.brandTitle}
        </span>
      </div>
    </footer>
  );
};

Object.assign(window, {
  Hero,
  Listings,
  Services,
  Process,
  Documents,
  Contact,
  Footer,
});
