// Octopak website — Print & Materials Guide (/guide)
// Body copy is real: generic, accurate print/materials knowledge, consistent
// with the facts confirmed elsewhere on the site (FAQ, Compare, family specs).
// Brand rules for this section: British/Singapore spelling, no em dashes,
// no banned words, "Customised" prefix on first mention of each family.
const { Button, Card } = window.OctopakDesignSystem_bc06ed;
const { Icon, WhatsAppGlyph, waLink, WA_DEFAULT, MediaSlot, ClosingCTA, FiveStepStrip, MoqLeadCallout, routeToHref } = window;
const { GUIDE_CHAPTERS } = window;
const { useState, useEffect, useRef } = React;

const HEADER_OFFSET = 92;
function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.scrollY - HEADER_OFFSET;
  window.scrollTo({ top: y, behavior: "smooth" });
}
// Robust jump for incoming anchors: re-corrects as image-slots/fonts settle.
function scrollToIdSettled(id) {
  const el = document.getElementById(id);
  if (!el) return;
  let last = -1;
  [0, 120, 320, 650].forEach((t) => setTimeout(() => {
    const y = Math.round(el.getBoundingClientRect().top + window.scrollY - HEADER_OFFSET);
    if (Math.abs(y - last) > 2) { last = y; window.scrollTo({ top: y, behavior: t === 0 ? "auto" : "smooth" }); }
  }, t));
}

/* ---- Chapter primitives -------------------------------------------------- */
function ChapterHead({ id, kicker, title }) {
  return (
    <header className="guide-chapter__head">
      {kicker && <p className="octo-eyebrow">{kicker}</p>}
      <h2 id={id} className="guide-chapter__title" tabIndex={-1}>{title}</h2>
    </header>
  );
}

// Standard chapter: body text with an optional alternating image column.
function GuideChapterBlock({ id, kicker, title, side = "right", image = true, children, watchout, cta }) {
  const media = image && (
    <figure className="guide-chapter__media">
      <MediaSlot id={`guide-img-${id}`} src={`assets/photos/guide-${id}.webp`} placeholder={`Placeholder for ${title} chapter image`} radius={14} style={{ aspectRatio: "4 / 3" }} />
    </figure>
  );
  return (
    <section className="guide-chapter" id={`sec-${id}`} aria-labelledby={id}>
      <ChapterHead id={id} kicker={kicker} title={title} />
      <div className={`guide-chapter__grid ${image ? `is-${side}` : "is-full"}`}>
        {image && side === "left" && media}
        <div className="guide-chapter__body">
          {children}
          {watchout && (
            <div className="guide-watchout" role="note">
              <span className="guide-watchout__icon"><Icon name="sparkle" size={18} /></span>
              <p>{watchout}</p>
            </div>
          )}
          {cta && (
            <p className="guide-chapter__cta">
              <a href={routeToHref(cta.to || "contact")} onClick={(e) => { e.preventDefault(); cta.onNavigate(cta.to || "contact"); }}>{cta.label} →</a>
            </p>
          )}
        </div>
        {image && side === "right" && media}
      </div>
    </section>
  );
}

/* ---- Comparison table (print methods) ------------------------------------ */
const PM_COLS = ["Method", "Best for", "Typical quantity", "Detail level", "Setup cost"];
const PM_ROWS = [
  { m: "Flexo", cells: ["Cups, paper bags", "Large", "Low to medium", "Medium"] },
  { m: "Offset", cells: ["Boxes, labels", "Large", "High", "High"] },
  { m: "Digital", cells: ["Short runs, prototypes", "Low", "Medium to high", "Low"] },
  { m: "Screen", cells: ["Specialty, darker stocks", "Low to medium", "Low to medium", "Medium"] },
];
// One-line answers for the FAQPage schema, matching the deep-dive chapters below.
const PM_ANSWERS = {
  Flexo: "Flexo suits cups and paper bags: solid colours and large runs, best when graphics are simple and quantities are real.",
  Offset: "Offset suits boxes and labels: sharper detail and consistent colour, worth the higher setup cost at volume.",
  Digital: "Digital suits short runs and prototypes: faster setup, higher unit cost, good for testing a design before a big run.",
  Screen: "Screen printing suits specialty cases like darker papers and unusual inks, less common in high-volume F&B but available when the brand calls for it.",
};

function GuideComparisonTable() {
  return (
    <div className="guide-table-wrap">
      <table className="guide-table">
        <thead>
          <tr>{PM_COLS.map((c) => <th key={c} className={c === "Method" ? "is-method" : ""}>{c}</th>)}</tr>
        </thead>
        <tbody>
          {PM_ROWS.map((r) => (
            <tr key={r.m}>
              <th scope="row">{r.m}</th>
              {r.cells.map((cell, i) => <td key={i}>{cell}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
      {/* Mobile: each method becomes a stacked card */}
      <div className="guide-table-cards">
        {PM_ROWS.map((r) => (
          <div className="guide-table-card" key={r.m}>
            <p className="guide-table-card__name">{r.m}</p>
            <dl>
              {r.cells.map((cell, i) => (
                <div key={i}><dt>{PM_COLS[i + 1]}</dt><dd>{cell}</dd></div>
              ))}
            </dl>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Chapter rail -------------------------------------------------------- */
function GuideRail({ active, onJump }) {
  const [open, setOpen] = useState(false);
  return (
    <aside className="guide-rail">
      <div className="guide-rail__sticky">
        <button className="guide-rail__toggle" aria-expanded={open} onClick={() => setOpen((v) => !v)}>
          <span>{open ? "Hide chapters" : "Chapters"}</span>
          <Icon name="chevron" size={18} />
        </button>
        <nav className={`guide-rail__list ${open ? "is-open" : ""}`} aria-label="Guide chapters">
          {GUIDE_CHAPTERS.map((c) => (
            <a key={c.id} href={`#${c.id}`}
              className={`guide-rail__link ${active === c.id ? "is-active" : ""}`}
              onClick={(e) => { e.preventDefault(); setOpen(false); onJump(c.id); }}>
              {c.label}
            </a>
          ))}
        </nav>
      </div>
    </aside>
  );
}

/* ---- Schema (Article / FAQPage / HowTo) ---------------------------------- */
function useGuideSchema() {
  useEffect(() => {
    const blocks = [
      {
        "@context": "https://schema.org", "@type": "Article",
        headline: "Print & Materials Guide for F&B Packaging",
        description: "A practical guide to the choices behind customised coffee cups, paper bags, and F&B packaging.",
        author: { "@type": "Organization", name: "Octopak" },
        publisher: { "@type": "Organization", name: "Octopak" },
        mainEntityOfPage: "https://octopak.com/guide",
      },
      {
        "@context": "https://schema.org", "@type": "FAQPage",
        mainEntity: PM_ROWS.map((r) => ({
          "@type": "Question",
          name: `When should I use ${r.m.toLowerCase()} printing?`,
          acceptedAnswer: { "@type": "Answer", text: PM_ANSWERS[r.m] },
        })),
      },
      {
        "@context": "https://schema.org", "@type": "HowTo",
        name: "What to send us for customised packaging",
        step: [
          { "@type": "HowToStep", name: "Send vector artwork", text: "Vector files (AI, EPS, PDF), or 300 dpi minimum for raster." },
          { "@type": "HowToStep", name: "Send brand colours", text: "Brand colours as Pantone codes where they exist." },
          { "@type": "HowToStep", name: "Send logo and fonts", text: "Logo, fonts or a fallback list, and a dieline if you have one." },
        ],
      },
    ];
    const nodes = blocks.map((b) => {
      const s = document.createElement("script");
      s.type = "application/ld+json";
      s.setAttribute("data-guide-schema", "");
      s.textContent = JSON.stringify(b);
      document.head.appendChild(s);
      return s;
    });
    return () => nodes.forEach((n) => n.remove());
  }, []);
}

/* ---- Page ---------------------------------------------------------------- */
function GuideView({ onNavigate, anchor }) {
  const [active, setActive] = useState("intro");
  const rootRef = useRef(null);
  useGuideSchema();

  // Scroll-spy
  useEffect(() => {
    const secs = Array.from(document.querySelectorAll(".guide-chapter"));
    if (!("IntersectionObserver" in window) || !secs.length) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) {
          const id = en.target.querySelector("[id]");
          if (id) setActive(id.id);
        }
      });
    }, { rootMargin: "-40% 0px -55% 0px", threshold: 0 });
    secs.forEach((s) => obs.observe(s));
    return () => obs.disconnect();
  }, []);

  // Jump to incoming anchor (from other pages / nav)
  useEffect(() => {
    if (anchor) { setActive(anchor); const t = setTimeout(() => scrollToIdSettled(anchor), 60); return () => clearTimeout(t); }
  }, [anchor]);

  const jump = (id) => { setActive(id); scrollToId(id); };
  const STRUCTURE_SUBS = [
    { h: "Cups", b: "Customised cups hold hot and cold drinks. Size and wall type follow the drink and how long it sits in the hand.", img: "assets/photos/folkyard-cups-stack-landscape.jpg" },
    { h: "Paper bags", b: "Customised paper bags carry the order out the door. Handle type and base follow the weight inside." },
    // No good example photo yet — hidden until one exists (same pattern as `hidden: true` families in Data.jsx).
    { h: "Boxes", b: "Customised boxes protect product and presentation. Board and closure follow what is going inside.", hidden: true },
    { h: "Wrappers", b: "Customised wrappers and greaseproof sheets brand and protect food in direct contact.", img: "assets/photos/hideout-paper-sandwich-wrapped-landscape.jpg" },
    // Explicit path rather than the index-based fallback below — this item's position in the
    // array shifts whenever a sibling is hidden, so an index-derived filename would silently break.
    { h: "Tote bags", b: "Customised tote bags carry the brand long after the sale, in canvas, non-woven fabric, or thermal insulated material. Material and size follow the use.", img: "assets/photos/guide-structure-5.webp" },
  ];

  return (
    <div className="guide" ref={rootRef}>
      {/* 1. Hero (text-led) */}
      <section className="guide-hero">
        <div className="octo-container">
          <p className="octo-eyebrow">Print &amp; Materials Guide</p>
          <h1 className="guide-hero__title">Print &amp; Materials Guide</h1>
          <p className="guide-hero__sub">A short walk through the choices behind customised F&amp;B packaging, so you arrive at the answer that fits your brand.</p>
          <div className="guide-hero__cta">
            <Button as="a" href={waLink(WA_DEFAULT)} target="_blank" rel="noreferrer" size="lg" variant="primary"
              iconLeft={<WhatsAppGlyph size={20} />}>Talk to us on WhatsApp</Button>
          </div>
        </div>
      </section>

      {/* Body: rail + chapters */}
      <div className="guide-body octo-container">
        <GuideRail active={active} onJump={jump} />
        <main className="guide-main">
          {/* 2. Intro */}
          <GuideChapterBlock id="intro" title="Intro" image={false}>
            <p>Customised packaging is about a few decisions, in this order: structure, material, print method, finish, colour, and the files you send us. This guide walks you through each.</p>
          </GuideChapterBlock>

          {/* 3. Structure */}
          <section className="guide-chapter" id="sec-structure" aria-labelledby="structure">
            <ChapterHead id="structure" kicker="Step one" title="Choosing your structure" />
            <div className="guide-chapter__body">
              <p>Structure first, because everything else depends on it. Match the format to what is going inside it.</p>
            </div>
            <div className="guide-substructure">
              {STRUCTURE_SUBS.filter((s) => !s.hidden).map((s, i) => (
                <article className="guide-subcard" key={s.h}>
                  <MediaSlot id={`guide-struct-${i}`} src={s.img || `assets/photos/guide-structure-${i + 1}.webp`} placeholder={`Placeholder for ${s.h} chapter image`} radius={12} shape="rect" style={{ aspectRatio: "4 / 3" }} />
                  <h3 className="guide-subcard__h">{s.h}</h3>
                  <p className="guide-subcard__b">{s.b}</p>
                </article>
              ))}
            </div>
          </section>

          {/* 4. Materials: paper */}
          <GuideChapterBlock id="materials-paper" kicker="Materials" title="Materials: paper" side="right">
            <p>Paper choice changes how your colours print, how the packaging feels, and how it ages. The three families to know are kraft, white coated, and greaseproof and food-grade barriers.</p>
          </GuideChapterBlock>

          {/* 5. Sustainability */}
          <GuideChapterBlock id="sustainability" kicker="Materials" title="Sustainability, honestly" side="left">
            <p>Sustainably sourced means something specific: FSC or PEFC certification, or disclosed recycled content. Look for one of those on your packaging if that's the promise you want to make to customers.</p>
          </GuideChapterBlock>

          {/* 6. Cup linings */}
          <GuideChapterBlock id="cup-linings" kicker="Materials" title="Cup linings" side="right">
            <p>Cups need a lining to hold liquid. The three options today are PE-lined (standard), PLA-lined (compostable in industrial composting), and aqueous-coated (newer, more recyclable). Each has trade-offs.</p>
          </GuideChapterBlock>

          {/* 7. Print methods overview */}
          <section className="guide-chapter" id="sec-print-methods" aria-labelledby="print-methods">
            <ChapterHead id="print-methods" kicker="Print methods" title="Print methods overview" />
            <div className="guide-chapter__body">
              <p>Print method is driven by quantity, paper, and how detailed your graphics are. Quick comparison below; deeper notes per method in the next four chapters.</p>
            </div>
            <GuideComparisonTable />
          </section>

          {/* 8-11. Method deep-dives */}
          <GuideChapterBlock id="flexo" kicker="Print methods" title="Flexographic printing" side="left">
            <p>The workhorse of F&amp;B packaging. Solid colours, large runs, ideal for cups and paper bags. Best when graphics are simple and quantities are real.</p>
          </GuideChapterBlock>
          <GuideChapterBlock id="offset" kicker="Print methods" title="Offset printing" side="right">
            <p>Detailed graphics, CMYK and Pantone matching, ideal for boxes and labels. Higher setup cost; lower marginal cost. Best at volume.</p>
          </GuideChapterBlock>
          <GuideChapterBlock id="digital" kicker="Print methods" title="Digital printing" side="left">
            <p>Short runs, prototypes, variable data. Faster setup, higher unit cost. Great for testing a design before committing to a big run.</p>
          </GuideChapterBlock>
          <GuideChapterBlock id="screen" kicker="Print methods" title="Screen printing" side="right">
            <p>Specialty cases: darker papers, unusual inks. Less common in high-volume F&amp;B but available when the brand calls for it.</p>
          </GuideChapterBlock>

          {/* 12-14. Finishes */}
          <GuideChapterBlock id="foil" kicker="Finishes" title="Finishes: foil stamping" side="left"
            cta={{ label: "Want foil on your order? Talk to us", onNavigate }}>
            <p>Hot foil pressed onto paper. Restrained luxury, most striking on kraft. Available on Octopak paper bags and boxes.</p>
          </GuideChapterBlock>
          <GuideChapterBlock id="emboss" kicker="Finishes" title="Finishes: emboss and deboss" side="right"
            cta={{ label: "Want emboss or deboss? Talk to us", onNavigate }}>
            <p>Embossing pushes the paper up; debossing pushes it down. Tactile, premium, best on boxes and bags. Available on Octopak paper bags and boxes.</p>
          </GuideChapterBlock>
          <GuideChapterBlock id="spot-uv" kicker="Finishes" title="Finishes: spot UV" side="left"
            cta={{ label: "See customised pouches", to: "products/pouches", onNavigate }}>
            <p>Selective gloss against matte. A subtle premium signal. Available on Octopak pouches.</p>
          </GuideChapterBlock>

          {/* 15. Colours */}
          <GuideChapterBlock id="colours" kicker="Colour" title="Choosing colours" side="right">
            <p>Pantone is a system for matching exact colours; CMYK is a process for printing them. If your brand red has to be exactly right, send a Pantone code. Kraft makes everything look warmer.</p>
          </GuideChapterBlock>

          {/* 16. What to send us */}
          <section className="guide-chapter" id="sec-what-to-send" aria-labelledby="what-to-send">
            <ChapterHead id="what-to-send" kicker="Working with us" title="What to send us" />
            <div className="guide-chapter__grid is-right">
              <div className="guide-chapter__body">
                <p>Vector files (AI, EPS, PDF), 300 dpi minimum for raster. Brand colours as Pantone codes where they exist. Logo, fonts (or fallback list), and a dieline if you have one. No print-ready file? Send what you have and we'll tell you what's workable and what needs redrawing. We don't design brands or logos from scratch.</p>
                <ul className="guide-checklist">
                  <li><Icon name="check" size={18} /> Vector artwork (AI, EPS, PDF), or 300 dpi raster</li>
                  <li><Icon name="check" size={18} /> Brand colours as Pantone codes where they exist</li>
                  <li><Icon name="check" size={18} /> Logo and fonts, or a fallback list</li>
                  <li><Icon name="check" size={18} /> A dieline if you have one</li>
                </ul>
              </div>
              <figure className="guide-chapter__media">
                <MediaSlot id="guide-img-what-to-send" src="assets/photos/guide-what-to-send.webp" placeholder="Placeholder for What to send us chapter image" radius={14} style={{ aspectRatio: "4 / 3" }} />
              </figure>
            </div>
          </section>
        </main>
      </div>

      {/* 17. From here (full width) */}
      <section className="guide-fromhere" id="sec-from-here" aria-labelledby="from-here">
        <div className="octo-container">
          <ChapterHead id="from-here" kicker="From here" title="From here" />
          <p className="guide-fromhere__lead">When the choices above are made, the rest is process. Here is how an order runs, and what to expect on minimums and timing.</p>
          <div style={{ marginTop: "var(--space-6)" }}>
            <FiveStepStrip />
          </div>
          <div style={{ marginTop: "var(--space-6)" }}>
            <MoqLeadCallout />
          </div>
        </div>
      </section>

      <ClosingCTA onNavigate={onNavigate} title="Ready to make these choices together?"
        sub="Tell us what you're packaging and we'll walk you through the decisions that actually matter for your job." />
    </div>
  );
}

Object.assign(window, { GuideView });
