// Octopak website — Product family template (/products/[family])
const { Button, Badge, Card } = window.OctopakDesignSystem_bc06ed;
const { PH, Flag, SectionHead, MediaSlot, ClosingCTA, Icon, WhatsAppGlyph, waLink, FAQList, routeToHref } = window;
const { FAMILIES_VISIBLE, familyBySlug, SPEC_ROWS } = window;

// Stock sizes for the vacuum-bags catalogue (locked; not customised).
const STOCK_SIZES = [
  { name: "Small", dim: "150 x 200mm" },
  { name: "Medium", dim: "200 x 300mm" },
  { name: "Large", dim: "300 x 400mm" },
];

// Stock-catalogue layout (stock: true families). No customised-template sections:
// no MOQ/lead callout, no print-method grid, no customised work strip, no guide cross-link.
function StockFamilyView({ fam, onNavigate }) {
  const waText = `Hello! I'd like to order ${fam.short}`;
  return (
    <div>
      {/* 1. Hero */}
      <section className="page-head">
        <div className="octo-container">
          <p className="crumbs">
            <a href={routeToHref("products")} onClick={(e) => { e.preventDefault(); onNavigate("products"); }}>Products</a>
            <span className="crumbs__sep">/</span><span>{fam.name}</span>
          </p>
          <div className="family-hero__grid">
            <div>
              <p className="octo-eyebrow">{fam.name} · stock range</p>
              <h1 className="page-head__title">{fam.h1}</h1>
              <p className="page-head__lead">{fam.wedge}</p>
              <div className="hero__cta" style={{ marginTop: "var(--space-5)" }}>
                <Button size="lg" variant="primary" onClick={() => onNavigate(`contact?family=${fam.slug}`)}>Start an order</Button>
                <Button as="a" href={waLink(waText)} target="_blank" rel="noreferrer" size="lg" variant="secondary"
                  iconLeft={<WhatsAppGlyph size={20} />}>Talk to us on WhatsApp</Button>
              </div>
            </div>
            <MediaSlot id={`fam-hero-${fam.slug}`} src={`assets/photos/${fam.slug}-hero.webp`} placeholder={`Photo of ${fam.short}`} radius={16} style={{ aspectRatio: "4 / 3" }} />
          </div>
        </div>
      </section>

      {/* 2. Sizes (replaces "What's customisable") */}
      <section className="section section--sunken section--tight">
        <div className="octo-container">
          <SectionHead eyebrow="Sizes" title="Three standard sizes." />
          <div className="specs">
            {STOCK_SIZES.map((s) => (
              <div className="spec" key={s.name}>
                <span className="spec__icon"><Icon name="ruler" size={22} /></span>
                <div>
                  <p className="spec__label">{s.name}</p>
                  <p className="spec__val">{s.dim}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 3. Order minimums + ready-to-ship callout */}
      <section className="section section--tight">
        <div className="octo-container">
          <div className="moq-box">
            <div>
              <span className="moq-box__label">Ready to ship</span>
              <Badge variant="eco">In stock</Badge>
            </div>
            <div>
              <p className="moq-box__note">
                Three standard sizes kept in stock and ready to ship. Minimum order of 100 bags,
                with free delivery on orders over $300.
              </p>
            </div>
            <Button variant="primary" onClick={() => onNavigate(`contact?family=${fam.slug}`)} style={{ marginLeft: "auto" }}>Start an order</Button>
          </div>
        </div>
      </section>

      {/* 4. Closing CTA */}
      <ClosingCTA onNavigate={onNavigate} title={`Order ${fam.short}.`}
        sub="Tell us the size and quantity you need and we'll confirm availability the same way we would for any stock item."
        waText={waText} prefillFamily={fam.slug} />
    </div>
  );
}

function FamilyView({ slug, onNavigate }) {
  const fam = familyBySlug(slug);
  if (fam.stock) return <StockFamilyView fam={fam} onNavigate={onNavigate} />;
  const idx = FAMILIES_VISIBLE.findIndex((f) => f.slug === fam.slug);
  const siblings = [FAMILIES_VISIBLE[(idx + 1) % FAMILIES_VISIBLE.length], FAMILIES_VISIBLE[(idx + 2) % FAMILIES_VISIBLE.length]];
  const waText = `Hello! I'd like to customise some ${fam.short} for my brand`;

  const famFaqs = fam.faqs || [
    { q: `What can I customise on ${fam.short}?`, a: null },
    { q: `What's the minimum order for ${fam.short}?`, a: null, flag: true },
    { q: `Which print methods suit ${fam.short}?`, a: null, flag: true },
    { q: `What artwork do you need from me?`, a: null },
  ];

  // Only count slots with a confirmed real photo — the strip renders exactly
  // that many tiles, no trailing placeholder boxes for photos that don't exist yet.
  const workPhotoCount = fam.workBrand ? (fam.workPhotos != null ? fam.workPhotos : (fam.imageHover ? 1 : 0)) : 0;

  return (
    <div>
      {/* 1. Family hero */}
      <section className="page-head">
        <div className="octo-container">
          <p className="crumbs">
            <a href={routeToHref("products")} onClick={(e) => { e.preventDefault(); onNavigate("products"); }}>Products</a>
            <span className="crumbs__sep">/</span><span>{fam.name}</span>
          </p>
          <div className="family-hero__grid">
            <div>
              <p className="octo-eyebrow">{fam.name}{fam.secondary && " · secondary range"}</p>
              <h1 className="page-head__title">{fam.h1}</h1>
              <p className="page-head__lead">{fam.wedge}</p>
              <div className="hero__cta" style={{ marginTop: "var(--space-5)" }}>
                <Button size="lg" variant="primary" onClick={() => onNavigate(`contact?family=${fam.slug}`)}>Start an enquiry</Button>
                <Button as="a" href={waLink(waText)} target="_blank" rel="noreferrer" size="lg" variant="secondary"
                  iconLeft={<WhatsAppGlyph size={20} />}>WhatsApp</Button>
              </div>
            </div>
            <MediaSlot id={`fam-hero-${fam.slug}`} src={fam.image || `assets/photos/${fam.slug}-hero.webp`} placeholder={`Real photo of customised ${fam.short}`} radius={16} style={{ aspectRatio: "4 / 3" }} />
          </div>
        </div>
      </section>

      {/* 2. What's customisable */}
      <section className="section section--sunken section--tight">
        <div className="octo-container">
          <SectionHead eyebrow="What's customisable" title="Made to your brand."
            intro="Almost anything is possible. It mostly comes down to price." />
          <div className="specs">
            {SPEC_ROWS.map((s) => {
              const famVal = fam.specs && fam.specs[s.key];
              if (famVal === false) return null; // family has confirmed this spec doesn't apply — omit the row
              return (
                <div className="spec" key={s.label}>
                  <span className="spec__icon"><Icon name={s.icon} size={22} /></span>
                  <div>
                    <p className="spec__label">{s.label}</p>
                    <p className="spec__val">
                      {famVal
                        ? famVal
                        : s.val
                          ? <>{s.val} <Flag>{s.flagText || "to confirm"}</Flag></>
                          : <><PH>options TBD</PH> <Flag /></>}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* 3. MOQ callout */}
      <section className="section section--tight">
        <div className="octo-container">
          <div className="moq-box">
            <div>
              <span className="moq-box__label">Starting MOQ</span>
              <span className="moq-box__num">{fam.moq ? fam.moq.num : "-"}</span>
            </div>
            <div>
              <p className="moq-box__note">
                {fam.moq
                  ? fam.moq.note
                  : <>Octopak's typical starting MOQ for {fam.short} is <Flag>number to confirm</Flag>. Higher quantities lower the unit price.</>}
              </p>
            </div>
            <Button variant="primary" onClick={() => onNavigate(`contact?family=${fam.slug}`)} style={{ marginLeft: "auto" }}>Start an enquiry</Button>
          </div>
        </div>
      </section>

      {/* 4. Finishes worth knowing (per-family; renders only when defined) */}
      {fam.finishes && fam.finishes.length > 0 && (
        <section className="section section--tight">
          <div className="octo-container">
            <SectionHead eyebrow="Finishes" title={`Looks you can get on ${fam.short}.`}
              intro="Outcome over technique. Here is what the finish actually does for your packaging." />
            <div className="grid-2" style={{ gap: "var(--space-4)" }}>
              {fam.finishes.map((f) => (
                <Card key={f.name} variant="default">
                  <h4 style={{ margin: "0 0 8px" }}>{f.name}</h4>
                  <p style={{ color: "var(--text-muted)", margin: 0, lineHeight: 1.6 }}>{f.body}</p>
                </Card>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* 5. Real work strip — hidden entirely until at least one real photo exists,
          and never pads out with empty placeholder boxes for photos that don't. */}
      {workPhotoCount > 0 && (
        <section className="section section--sunken">
          <div className="octo-container">
            <SectionHead eyebrow="Real work" title={`${fam.name} we've customised.`} />
            <div className="workstrip">
              {Array.from({ length: workPhotoCount }, (_, i) => (
                <div className="workstrip__item" key={i}>
                  <MediaSlot id={`fam-work-${fam.slug}-${i}`}
                    src={(i === 0 && fam.imageHover) || `assets/photos/${fam.slug}-work-${i + 1}.webp`}
                    placeholder="Customised work photo" radius={12} shape="rect" style={{ aspectRatio: "4 / 3" }} />
                  <span className="workstrip__cap">{fam.workBrand}</span>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* 6. Common questions */}
      <section className="section">
        <div className="octo-container octo-container--narrow">
          <SectionHead eyebrow="Common questions" title={`About ${fam.short}.`} center />
          <FAQList items={famFaqs} onNavigate={onNavigate} />
          <p style={{ textAlign: "center", marginTop: "var(--space-5)" }}>
            <a href={routeToHref("faq")} onClick={(e) => { e.preventDefault(); onNavigate("faq"); }}>See all questions →</a>
          </p>
        </div>
      </section>

      {/* 6.5 Print & Materials Guide cross-link */}
      <section className="section section--tight" style={{ paddingTop: 0 }}>
        <div className="octo-container">
          <a className="guide-xlink" href={routeToHref(`guide#${fam.guideAnchor || "intro"}`)}
            onClick={(e) => { e.preventDefault(); onNavigate(`guide#${fam.guideAnchor || "intro"}`); }}>
            <span className="guide-xlink__icon"><Icon name="file" size={22} /></span>
            <span className="guide-xlink__text">
              <strong>See the choices behind your packaging</strong>
              <span>Materials, print methods, finishes and file specs, all in our Print &amp; Materials Guide.</span>
            </span>
            <Icon name="arrow-right" size={22} className="guide-xlink__arrow" />
          </a>
        </div>
      </section>

      {/* 7. Closing + siblings */}
      <ClosingCTA onNavigate={onNavigate} title={`Tell us about your ${fam.short}.`} sub={fam.closingSub} waText={waText} prefillFamily={fam.slug} />

      <section className="section section--tight" style={{ paddingTop: 0 }}>
        <div className="octo-container">
          <SectionHead eyebrow="Keep exploring" title="Other ranges." />
          <div className="grid-2">
            {siblings.map((s) => (
              <a key={s.slug} className="wedge-card" href={routeToHref(`products/${s.slug}`)}
                onClick={(e) => { e.preventDefault(); onNavigate(`products/${s.slug}`); }} style={{ textDecoration: "none", flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
                <span>
                  <h3 className="wedge-card__title">{s.name}</h3>
                  <p className="wedge-card__body" style={{ marginTop: 4 }}>{s.wedge}</p>
                </span>
                <Icon name="arrow-right" size={26} className="wedge-card__icon" />
              </a>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { FamilyView });
