// Kennisbank — SEO-blog: overzicht + artikelpagina's.
// Artikeldata komt uit public/kennisbank-data.js (window.KENNISBANK_ARTIKELEN),
// gedeeld met de server (src/lib/seo.js) voor meta-tags + sitemap.

function getArtikelen() {
  return (typeof window !== "undefined" && window.KENNISBANK_ARTIKELEN) || [];
}
function getArtikel(slug) {
  return getArtikelen().find(a => a.slug === slug) || null;
}

// Vaste beeldstandaard: echte werkplaatsfoto's, deterministisch per artikel verdeeld.
const BLOG_PHOTOS = [
  "/photos/diagnose/IMG_4606.JPG", "/photos/diagnose/IMG_4607.JPG", "/photos/diagnose/IMG_4609.JPG",
  "/photos/diagnose/IMG_4610.JPG", "/photos/diagnose/IMG_4611.JPG", "/photos/diagnose/IMG_4614.JPG",
  "/photos/diagnose/IMG_4615.JPG", "/photos/diagnose/IMG_4616.JPG", "/photos/diagnose/IMG_4617.JPG",
  "/photos/diagnose/IMG_4618.JPG", "/photos/diagnose/IMG_4624.JPG", "/photos/diagnose/IMG_4625.JPG",
  "/photos/diagnose/IMG_4630.JPG", "/photos/diagnose/IMG_4632.JPG",
  "/photos/diagnose/IMG_4626%20kopie%20klein.jpg", "/photos/diagnose/Foto%20Diagnose%20apparaat.JPG",
];
function photoFor(slug, offset) {
  let h = 0;
  for (let i = 0; i < (slug || "").length; i++) h = (h * 31 + slug.charCodeAt(i)) >>> 0;
  return BLOG_PHOTOS[(h + (offset || 0)) % BLOG_PHOTOS.length];
}

// Herbruikbare afbeelding met vaste stijl (rond, 16:9, zachte schaduw)
function ArticleImage({ src, caption, style }) {
  return (
    <figure style={{ margin: "28px 0", ...style }}>
      <div role="img" aria-label={caption || "Werkplaats Garage DéDé Vijfhuizen"} style={{
        width: "100%", aspectRatio: "16 / 9", borderRadius: 14, overflow: "hidden",
        border: "1px solid var(--border)", boxShadow: "var(--shadow-soft)",
        backgroundImage: `url('${src}')`, backgroundSize: "cover", backgroundPosition: "center",
      }}/>
      {caption && <figcaption className="text-muted" style={{ fontSize: 12, marginTop: 8, textAlign: "center" }}>{caption}</figcaption>}
    </figure>
  );
}

// Icoon per categorie (val terug op boek)
const CAT_ICON = {
  "APK": "Apk", "Onderhoud": "Wrench", "Banden & seizoen": "Tire",
  "Airco": "Snow", "Diagnose": "Diag", "EV & hybride": "Bolt", "Kosten & tips": "Sparkle",
  "Reparatie": "Cog", "Schade & ruit": "ShieldCheck",
};
function catIcon(cat) { return I[CAT_ICON[cat]] || I.Diag; }

// Interne link: categorie → relevante dienstpagina (SEO-structuur)
const CAT_SERVICE = {
  "APK": { screen: "service-apk", label: "APK keuring" },
  "Onderhoud": { screen: "service-onderhoud", label: "Onderhoudsbeurt" },
  "Reparatie": { screen: "service-reparatie", label: "Auto reparatie" },
  "Diagnose": { screen: "service-diagnose", label: "Diagnose" },
  "Airco": { screen: "service-airco", label: "Airco service" },
  "Banden & seizoen": { screen: "service-banden", label: "Banden & wielen" },
  "Schade & ruit": { screen: "service-ruitschade", label: "Ruitschade" },
  "EV & hybride": { screen: "service-onderhoud", label: "Onderhoud" },
  "Kosten & tips": { screen: "diensten", label: "Alle diensten" },
};

// Platte-tekst body renderen: opeenvolgende "- "-regels worden een lijst,
// overige regels alinea's. Werkt ook als een inleidende regel + bullets in
// hetzelfde blok staan.
function ArticleBody({ text }) {
  const lines = String(text || "").split("\n");
  const out = [];
  let para = [], bullets = [];
  const flushPara = () => { if (para.length) { out.push({ t: "p", v: para.join(" ") }); para = []; } };
  const flushBul = () => { if (bullets.length) { out.push({ t: "ul", v: bullets.slice() }); bullets = []; } };
  for (const raw of lines) {
    const l = raw.trim();
    if (!l) { flushPara(); flushBul(); continue; }
    if (l.startsWith("- ")) { flushPara(); bullets.push(l.replace(/^-\s+/, "")); }
    else { flushBul(); para.push(l); }
  }
  flushPara(); flushBul();
  return (
    <>
      {out.map((b, i) => b.t === "ul" ? (
        <ul key={i} style={{ margin: "0 0 18px", paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 8 }}>
          {b.v.map((li, j) => (
            <li key={j} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 16, lineHeight: 1.65 }}>
              <I.Check size={15} style={{ color: "var(--accent)", marginTop: 5, flexShrink: 0 }}/>
              <span>{li}</span>
            </li>
          ))}
        </ul>
      ) : (
        <p key={i} style={{ fontSize: 16, lineHeight: 1.75, margin: "0 0 18px", color: "var(--text)" }}>{b.v}</p>
      ))}
    </>
  );
}

// ─── OVERZICHT ──────────────────────────────────────────
function Kennisbank({ onNav }) {
  const artikelen = getArtikelen();
  const categories = ["Alle", ...Array.from(new Set(artikelen.map(a => a.category)))];
  const [cat, setCat] = React.useState("Alle");
  const list = cat === "Alle" ? artikelen : artikelen.filter(a => a.category === cat);

  return (
    <div>
      {/* Hero */}
      <section style={{ borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
        <div style={{ maxWidth: 1080, margin: "0 auto", padding: "72px 32px 48px" }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Kennisbank</div>
          <h1 className="display" style={{ fontSize: 56, marginBottom: 18, maxWidth: 780 }}>
            Alles over <span style={{ color: "var(--accent)", fontStyle: "italic", fontWeight: 700 }}>autoonderhoud</span> & APK
          </h1>
          <p className="subhead" style={{ maxWidth: 660, fontSize: 19 }}>
            Praktische uitleg, tips en antwoorden op veelgestelde vragen — van APK en onderhoud
            tot banden, airco en diagnose. Geschreven door de monteurs van Garage DéDé in Vijfhuizen.
          </p>
        </div>
      </section>

      {/* Categorie-filter */}
      <section style={{ padding: "28px 0 0", position: "sticky", top: 73, zIndex: 5, background: "var(--bg)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ maxWidth: 1080, margin: "0 auto", padding: "0 32px 20px", display: "flex", gap: 8, flexWrap: "wrap" }}>
          {categories.map(c => (
            <button key={c} onClick={() => setCat(c)}
              className={c === cat ? "pill accent" : "pill"}
              style={{ cursor: "pointer", fontSize: 13, padding: "8px 14px" }}>
              {c}
            </button>
          ))}
        </div>
      </section>

      {/* Artikel-grid */}
      <section style={{ padding: "40px 0 80px" }}>
        <div style={{ maxWidth: 1080, margin: "0 auto", padding: "0 32px" }}>
          {list.length === 0 ? (
            <div className="placeholder" style={{ height: 160 }}>Binnenkort meer artikelen…</div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
              {list.map(a => {
                const Icon = catIcon(a.category);
                const excerpt = String(a.intro || "").split(/\n\n+/)[0].slice(0, 130);
                return (
                  <button key={a.slug} onClick={() => onNav("artikel-" + a.slug)}
                    className="card lift" style={{ padding: 0, textAlign: "left", cursor: "pointer", color: "var(--text)",
                                                   display: "flex", flexDirection: "column", overflow: "hidden" }}>
                    <div style={{ width: "100%", aspectRatio: "16 / 9", position: "relative",
                                  backgroundImage: `url('${photoFor(a.slug, 0)}')`, backgroundSize: "cover", backgroundPosition: "center" }}>
                      <span style={{ position: "absolute", top: 12, left: 12, display: "inline-flex", alignItems: "center", gap: 6,
                                     padding: "5px 10px", borderRadius: 999, fontSize: 11, fontWeight: 600, color: "var(--crème)",
                                     background: "rgba(11,11,12,0.72)", border: "1px solid rgba(255,255,255,0.12)" }}>
                        <Icon size={12} style={{ color: "var(--accent)" }}/> {a.category}
                      </span>
                    </div>
                    <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 10, flex: 1 }}>
                      <h2 style={{ fontSize: 17, fontWeight: 700, lineHeight: 1.3, letterSpacing: "-0.01em" }}>{a.title}</h2>
                      <p className="text-muted" style={{ fontSize: 14, lineHeight: 1.5, margin: 0 }}>{excerpt}…</p>
                      <div style={{ marginTop: "auto", paddingTop: 6, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <span className="text-muted" style={{ fontSize: 12 }}>{a.readMin || 4} min lezen</span>
                        <span style={{ color: "var(--accent)", fontSize: 13, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 6 }}>
                          Lees meer <I.ArrowRight size={13}/>
                        </span>
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

// ─── ARTIKEL ────────────────────────────────────────────
function Artikel({ slug, onNav }) {
  const a = getArtikel(slug);
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [slug]);
  if (!a) {
    return (
      <div style={{ maxWidth: 720, margin: "0 auto", padding: "80px 32px", textAlign: "center" }}>
        <h1 className="headline" style={{ marginBottom: 16 }}>Artikel niet gevonden</h1>
        <button className="btn btn-primary" onClick={() => onNav("kennisbank")}>Terug naar de kennisbank</button>
      </div>
    );
  }
  const related = (a.related || [])
    .map(getArtikel).filter(Boolean).slice(0, 3);
  // Fallback related: zelfde categorie
  const relatedList = related.length ? related
    : getArtikelen().filter(x => x.category === a.category && x.slug !== a.slug).slice(0, 3);

  return (
    <article>
      {/* Header met hero-foto */}
      <section style={{ position: "relative", borderBottom: "1px solid var(--border)", overflow: "hidden" }}>
        <div aria-hidden style={{ position: "absolute", inset: 0,
          backgroundImage: `url('${photoFor(a.slug, 0)}')`, backgroundSize: "cover", backgroundPosition: "center", opacity: 0.4 }}/>
        <div aria-hidden style={{ position: "absolute", inset: 0,
          background: "linear-gradient(180deg, rgba(11,11,12,0.72) 0%, rgba(11,11,12,0.94) 100%)" }}/>
        <div style={{ position: "relative", maxWidth: 800, margin: "0 auto", padding: "40px 32px 48px" }}>
          <button onClick={() => onNav("kennisbank")} className="btn btn-ghost btn-sm" style={{ marginBottom: 24 }}>
            <I.ArrowLeft size={14}/> Kennisbank
          </button>
          <div className="eyebrow" style={{ marginBottom: 14 }}>{a.category} · {a.readMin || 4} min lezen</div>
          <h1 className="headline" style={{ fontSize: 40, lineHeight: 1.12 }}>{a.title}</h1>
        </div>
      </section>

      {/* Intro + secties */}
      <section style={{ padding: "48px 0 40px" }}>
        <div style={{ maxWidth: 800, margin: "0 auto", padding: "0 32px" }}>
          <div style={{ fontSize: 18, lineHeight: 1.75, color: "var(--text)", marginBottom: 8 }}>
            <ArticleBody text={a.intro}/>
          </div>
          {(a.sections || []).map((sec, i) => (
            <React.Fragment key={i}>
              <div style={{ marginTop: 36 }}>
                <h2 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 14 }}>{sec.h2}</h2>
                <ArticleBody text={sec.body}/>
              </div>
              {(i === 1 || i === 3) && a.sections.length > i + 1 && (
                <ArticleImage src={photoFor(a.slug, i === 1 ? 5 : 9)} caption="Werkplaats Garage DéDé — Vijfhuizen"/>
              )}
            </React.Fragment>
          ))}
        </div>
      </section>

      {/* FAQ */}
      {a.faq && a.faq.length > 0 && (
        <section style={{ padding: "48px 0", background: "var(--surface)", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)" }}>
          <div style={{ maxWidth: 800, margin: "0 auto", padding: "0 32px" }}>
            <h2 className="headline" style={{ fontSize: 30, marginBottom: 28 }}>Veelgestelde vragen</h2>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {a.faq.map((qa, i) => <FaqRow key={i} q={qa.q} a={qa.a}/>)}
            </div>
          </div>
        </section>
      )}

      {/* CTA */}
      <section style={{ padding: "56px 32px" }}>
        <div className="card" style={{ maxWidth: 800, margin: "0 auto", padding: 40, textAlign: "center",
                                        background: "linear-gradient(135deg, var(--surface) 0%, color-mix(in oklab, var(--accent) 12%, var(--surface)) 100%)",
                                        border: "1px solid color-mix(in oklab, var(--accent) 28%, var(--border))" }}>
          <h2 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 10 }}>Hulp nodig met uw auto?</h2>
          <p className="text-muted" style={{ fontSize: 16, marginTop: 0, marginBottom: 24, maxWidth: 520, marginLeft: "auto", marginRight: "auto" }}>
            Garage DéDé in Vijfhuizen helpt u verder — APK, onderhoud, diagnose en meer. Plan online een afspraak of bel ons.
          </p>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
            <button className="btn btn-primary btn-lg" onClick={() => onNav("boeking")}>Afspraak maken <I.ArrowRight size={18}/></button>
            {CAT_SERVICE[a.category] && (
              <button className="btn btn-ghost btn-lg" onClick={() => onNav(CAT_SERVICE[a.category].screen)}>
                Meer over {CAT_SERVICE[a.category].label} <I.ArrowRight size={16}/>
              </button>
            )}
            <a href="tel:+31235451809" className="btn btn-ghost btn-lg"><I.Phone size={16}/> 023 - 545 1809</a>
          </div>
        </div>
      </section>

      {/* Gerelateerd */}
      {relatedList.length > 0 && (
        <section style={{ padding: "0 32px 80px" }}>
          <div style={{ maxWidth: 1080, margin: "0 auto" }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Lees ook</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
              {relatedList.map(r => (
                <button key={r.slug} onClick={() => onNav("artikel-" + r.slug)}
                  className="card lift" style={{ padding: 22, textAlign: "left", cursor: "pointer", color: "var(--text)" }}>
                  <span className="text-muted" style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase" }}>{r.category}</span>
                  <h3 style={{ fontSize: 16, fontWeight: 700, lineHeight: 1.3, margin: "8px 0 0" }}>{r.title}</h3>
                </button>
              ))}
            </div>
          </div>
        </section>
      )}
    </article>
  );
}

function FaqRow({ q, a }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ borderBottom: "1px solid var(--border)" }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: "100%", textAlign: "left", padding: "18px 0", background: "transparent", border: 0,
        display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, cursor: "pointer",
        color: "var(--text)", fontFamily: "inherit",
      }}>
        <span style={{ fontSize: 16, fontWeight: 600 }}>{q}</span>
        <span style={{ width: 24, height: 24, borderRadius: 999, background: "var(--surface-2)", border: "1px solid var(--border)",
                       display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                       transition: "transform .2s ease", transform: open ? "rotate(45deg)" : "none" }}>
          <I.Plus size={14}/>
        </span>
      </button>
      {open && <div style={{ padding: "0 0 18px", color: "var(--text-muted)", fontSize: 15, lineHeight: 1.65 }}>{a}</div>}
    </div>
  );
}

window.Kennisbank = Kennisbank;
window.Artikel = Artikel;
