// Sarpah — page templates
// Generic Page renders any markdown route; specialised templates handle Home,
// audience pages (Buyers/Originators/Sub-agents), section indices, and forms.

const { useEffect, useMemo, useState, useRef } = React;
const S = window.Sarpah;

/* ============================================================
   Helpers
   ============================================================ */

function Crumbs({ trail }) {
  return (
    <div className="page-head__breadcrumbs">
      {trail.map((c, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="sep">/</span>}
          {c.slug ? <a href={"#" + c.slug}>{c.label}</a> : <span>{c.label}</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

function buildTrail(route) {
  const trail = [{ slug: "/", label: "Sarpah" }];
  if (!route || route.slug === "/") return trail;
  if (route.section === "products") {
    trail.push({ slug: "/products/fertilizers", label: "Products" });
    if (route.group && route.slug !== `/products/${route.group.toLowerCase().replace(/\s+/g, "-")}`) {
      const groupRoot = window.SARPAH_ROUTES.find(r => r.section === "products" && r.group === route.group && r.order === 0);
      if (groupRoot && groupRoot.slug !== route.slug) {
        trail.push({ slug: groupRoot.slug, label: route.group });
      }
    }
  } else if (route.section === "compliance" && route.slug !== "/compliance") {
    trail.push({ slug: "/compliance", label: "Compliance" });
  } else if (route.section === "origination" && route.slug !== "/origination") {
    trail.push({ slug: "/origination", label: "Corridors" });
  } else if (route.section === "insights") {
    trail.push({ slug: "/insights/russia-kenya-wheat-corridor-2026", label: "Insights" });
  } else if (route.section === "forms") {
    trail.push({ slug: "/", label: "Talk to us" });
  }
  trail.push({ label: route.title });
  return trail;
}

/* ============================================================
   Section sub-nav (products, compliance, origination)
   ============================================================ */

function SectionNav({ route }) {
  const path = useLocation();
  if (!route) return null;
  let label = null, items = [];
  if (route.section === "products") {
    label = "Products";
    items = [
      { slug: "/products/fertilizers", label: "Fertilizers" },
      { slug: "/products/grain", label: "Grain" },
      { slug: "/products/edible-oils", label: "Edible Oils" },
      { slug: "/products/food", label: "Food" },
      { slug: "/products/petroleum", label: "Petroleum" },
      { slug: "/products/timber", label: "Timber" },
    ];
  } else if (route.section === "compliance") {
    label = "Compliance";
    items = window.SARPAH_ROUTES.filter(r => r.section === "compliance")
      .map(r => ({ slug: r.slug, label: r.title.split(" — ")[0].replace("ICC ", "") }));
  } else if (route.section === "origination") {
    label = "Corridors";
    items = window.SARPAH_ROUTES.filter(r => r.section === "origination")
      .map(r => ({ slug: r.slug, label: r.title.replace(" Corridor", "") }));
  } else {
    return null;
  }
  return (
    <div className="section-nav no-print">
      <div className="section-nav__inner">
        <div className="section-nav__label">{label}</div>
        <div className="section-nav__items">
          {items.map(it => (
            <a key={it.slug} href={"#" + it.slug}
               className={path === it.slug || (path.startsWith(it.slug) && it.slug !== "/products/fertilizers" && it.slug !== "/compliance" && it.slug !== "/origination") ? "is-active" : ""}>
              {it.label}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}
function useLocation() { return S.useRoute(); }

/* ============================================================
   Page header
   ============================================================ */

function PageHead({ route, eyebrow, dark, photo }) {
  const trail = buildTrail(route);
  const meta = [];
  if (route.section === "compliance") meta.push("Regulatory standard");
  if (route.section === "origination") meta.push("Origination corridor");
  if (route.section === "insights") meta.push("Field note");
  if (route.section === "products") meta.push("Product brief");
  const imgKey = photo === false ? null : (photo === true ? window.SarpahImg.pickFor(route) : photo);
  if (imgKey) {
    return (
      <header className="page-head page-head--photo page-head--md">
        <div className="page-head__bg" style={{backgroundImage: `url(${window.SarpahImg.urlFor(imgKey, 1800, 75)})`}} aria-hidden="true" />
        <div className="page-head__scrim" aria-hidden="true" />
        <div className="page-head__inner page-head__inner--photo">
          <Crumbs trail={trail} />
          {(eyebrow || meta.length > 0) && (
            <div className="ribbon ribbon--on-photo">{eyebrow || meta.join(" · ")}</div>
          )}
          <h1 className="page-head__title page-head__title--on-photo">{route.title}</h1>
          {route.description && <p className="page-head__lede page-head__lede--on-photo">{route.description}</p>}
        </div>
      </header>
    );
  }
  return (
    <header className={"page-head" + (dark ? " page-head--ink" : "")}>
      <div className="page-head__inner">
        <Crumbs trail={trail} />
        {(eyebrow || meta.length > 0) && (
          <div className="ribbon">{eyebrow || meta.join(" · ")}</div>
        )}
        <h1 className="page-head__title">{route.title}</h1>
        {route.description && <p className="page-head__lede">{route.description}</p>}
      </div>
    </header>
  );
}

/* ============================================================
   Generic markdown page
   ============================================================ */

function MarkdownPage({ route }) {
  const md = S.useMarkdown(route.file);
  const isInsight = route.section === "insights";
  const proseClass = "prose" + (isInsight ? " has-dropcap" : "");

  // Build TOC from h2s
  const toc = md.headings ? md.headings.filter(h => h.level === 2) : [];

  // Find "Related" links: same group siblings
  const siblings = window.SARPAH_ROUTES
    .filter(r => r.group === route.group && r.slug !== route.slug && r.section === route.section)
    .slice(0, 6);

  return (
    <>
      <PageHead route={route} photo={isInsight ? window.SarpahImg.pickFor(route) : undefined} />
      <SectionNav route={route} />
      <div className="body-two-col">
        <aside className="toc-side no-print" aria-label="On this page">
          {toc.length > 0 && <>
            <h4>On this page</h4>
            <ul>
              {toc.map(h => (
                <li key={h.id}><a href={"#" + window.location.hash.replace(/^#/, "") + "#" + h.id}
                                  onClick={(e) => { e.preventDefault(); document.getElementById(h.id)?.scrollIntoView({behavior:"smooth", block:"start"}); }}>{h.text}</a></li>
              ))}
            </ul>
          </>}
          {siblings.length > 0 && <>
            <h4 style={{marginTop: 24}}>Related</h4>
            <ul>
              {siblings.map(r => (
                <li key={r.slug}><a href={"#" + r.slug}>{r.title.replace(" — ", " · ")}</a></li>
              ))}
            </ul>
          </>}
          <h4 style={{marginTop: 24}}>Talk to us</h4>
          <ul>
            <li><a href="#/talk/buyer">Buyer enquiry →</a></li>
            <li><a href="#/talk/mandate">Mandate enquiry →</a></li>
          </ul>
        </aside>
        <article>
          {md.loading && <div style={{color: "var(--ink-3)"}}>Loading…</div>}
          {md.error && <div style={{color: "var(--accent-ink)"}}>Could not load: {md.error}</div>}
          {md.html && <div className={proseClass} dangerouslySetInnerHTML={{__html: md.html}} />}
        </article>
      </div>
    </>
  );
}

/* ============================================================
   Home page
   ============================================================ */

function Home() {
  return (
    <>
      <section className="hero hero--photo">
        <div className="hero__bg" style={{backgroundImage: `url(${window.SarpahImg.urlFor("container-ship-aerial", 2200, 80)})`}} aria-hidden="true" />
        <div className="hero__scrim" aria-hidden="true" />
        <div className="hero__inner hero__inner--photo">
          <div className="hero__lockup">
            <div className="ribbon ribbon--on-photo">Mandated Origination Agent</div>
            <h1 className="hero__title hero__title--on-photo">
              Russia–CIS commodities, <em>delivered</em> to East African institutions.
            </h1>
            <p className="hero__sub hero__sub--on-photo">
              The channel between upstream producers in the Black Sea, Baltic, Caspian and Far East and the buyers, millers and tender boards of Kenya and the EAC.
            </p>
            <div className="hero__cta">
              <a href="#/buyer-process" className="btn btn--lg btn--accent">Start a buyer enquiry <Arrow/></a>
              <a href="#/originators" className="btn btn--lg btn--on-photo">For originators <Arrow/></a>
            </div>
          </div>
        </div>
      </section>

      {/* Stat strip — operational, not headline metrics */}
      <section className="section--tight">
        <div className="container-wide">
          <div className="stat-strip">
            <div className="stat">
              <div className="stat__num"><em>6</em></div>
              <div className="stat__label">Commodity lines</div>
              <div className="stat__note">Fertilizer, grain, edible oils, food, petroleum, timber — all institutional flows.</div>
            </div>
            <div className="stat">
              <div className="stat__num"><em>4</em></div>
              <div className="stat__label">Origination corridors</div>
              <div className="stat__note">Black Sea, Baltic, Caspian and Far East — vetted producers and load-port logistics.</div>
            </div>
            <div className="stat">
              <div className="stat__num"><em>EAC</em></div>
              <div className="stat__label">Destination scope</div>
              <div className="stat__note">Kenya, Tanzania, Uganda, Rwanda, Burundi, South Sudan and the southern DRC copper belt.</div>
            </div>
            <div className="stat">
              <div className="stat__num">UCP <em>600</em></div>
              <div className="stat__label">Documentary discipline</div>
              <div className="stat__note">DLC, SBLC and URDG 758 instruments. Cargo flows on bank paper, not handshakes.</div>
            </div>
          </div>
        </div>
      </section>

      {/* Three doors */}
      <section className="section--tight">
        <div className="container-wide">
          <div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32}}>
            <div>
              <div className="ribbon">Three audiences</div>
              <h2 className="display" style={{fontSize: "var(--t-3xl)", marginTop: 12}}>Pick the door that fits.</h2>
            </div>
            <a href="#/about" className="link">How Sarpah works <Arrow/></a>
          </div>
          <div className="three-doors">
            {[
              { num:"01", slug:"/buyer-process", eyebrow:"Buyers", title:"East African institutional buyers", desc:"Millers, blenders, tender boards. Documentary credit, KEBS PVoC, KEPHIS, EAC CET — handled in-house." },
              { num:"02", slug:"/originators", eyebrow:"Originators", title:"Upstream producers & traders", desc:"Mandate the East African leg. NCNDA / IMFPA, irrevocable fee protection, local agency presence." },
              { num:"03", slug:"/sub-agents", eyebrow:"Sub-agents", title:"Mandated representatives", desc:"EAC and Southern DRC introducers — terms, training, and a direct line to working files." },
            ].map(d => (
              <a key={d.slug} href={"#" + d.slug} className="door">
                <div className="door__num">{d.num}</div>
                <div>
                  <div className="ribbon" style={{marginBottom: 16}}>{d.eyebrow}</div>
                  <h3>{d.title}</h3>
                  <p>{d.desc}</p>
                </div>
                <div className="door__foot">
                  <span>Open the {d.eyebrow.toLowerCase()} flow</span>
                  <Arrow/>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Editorial / pull */}
      <section className="section section--ink">
        <div className="container-wide" style={{display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 64, alignItems: "center"}}>
          <div>
            <div className="ribbon" style={{marginBottom: 24}}>The discipline of the channel</div>
            <p className="pull" style={{color: "var(--paper)", maxWidth: "22ch"}}>
              <em>One mandated agent.</em> Local jurisdiction. Documentary discipline. No retail noise.
            </p>
            <p style={{color: "rgba(244,241,234,0.75)", maxWidth: "44ch", marginTop: 32, fontSize: "var(--t-md)", lineHeight: 1.6}}>
              We do not sell to households, we do not retail. Sarpah’s only customer is the institutional importer or mandated principal — and that constraint is what lets the channel work cleanly under ICC instruments.
            </p>
          </div>
          <div style={{borderLeft: "1px solid var(--accent)", paddingLeft: 48}}>
            <div className="ribbon" style={{color: "rgba(244,241,234,0.55)", marginBottom: 16}}>What we hold</div>
            <ul style={{listStyle: "none", padding: 0, margin: 0, fontFamily: "var(--serif)", fontSize: "var(--t-lg)", lineHeight: 1.6, color: "var(--paper)"}}>
              <li style={{borderBottom: "1px solid var(--accent)", padding: "12px 0"}}>NCNDA &amp; IMFPA on every working file</li>
              <li style={{borderBottom: "1px solid var(--accent)", padding: "12px 0"}}>URDG 758 bid-bond capability</li>
              <li style={{borderBottom: "1px solid var(--accent)", padding: "12px 0"}}>UCP 600 documentary-credit fluency</li>
              <li style={{padding: "12px 0"}}>KEBS, KEPHIS, KRA, FAFB working contacts</li>
            </ul>
          </div>
        </div>
      </section>

      {/* Featured products */}
      <section className="section">
        <div className="container-wide">
          <div className="index-group__head">
            <h3>Featured product lines</h3>
            <span className="count">Russia · CIS origin</span>
          </div>
          <div className="card-grid">
            {[
              { slug:"/products/grain/wheat-12-5-protein", t:"Wheat — 12.5% protein", d:"Premium bread-wheat to Kenyan and EAC millers. Ex Black Sea / Baltic. ISO 7970, FOSFA / GAFTA-compatible.", tag:"Grain", img:"wheat-field" },
              { slug:"/products/fertilizers/urea-grade-b", t:"Urea — Grade B", d:"GOST 2081-2010 highest grade. NCPB-tender ready, FAFB-aligned. Granular, biuret ≤ 1.4%.", tag:"Fertilizer", img:"fertilizer-bags" },
              { slug:"/products/edible-oils/sunflower-oil", t:"Sunflower oil", d:"Crude and refined ex Black Sea origin. KEBS PVoC Route A or B. Flexitank or 1L PET retail-pack.", tag:"Oils", img:"oil-storage-tanks" },
            ].map(c => (
              <a key={c.slug} href={"#" + c.slug} className="card card--photo">
                <div className="card__photo" style={{backgroundImage: `url(${window.SarpahImg.urlFor(c.img, 900, 75)})`}} aria-hidden="true" />
                <div className="card__body">
                  <span className="tag">{c.tag}</span>
                  <h4 className="card__title">{c.t}</h4>
                  <p className="card__desc">{c.d}</p>
                  <div className="card__foot"><span>Open product brief</span> <Arrow/></div>
                </div>
              </a>
            ))}
          </div>
          <div style={{marginTop: 24, display: "flex", gap: 16, flexWrap: "wrap"}}>
            <a href="#/products/fertilizers" className="link">All fertilizers ({window.SARPAH_ROUTES.filter(r => r.group === "Fertilizers" && r.order !== 0).length}) <Arrow/></a>
            <a href="#/products/grain" className="link">All grain <Arrow/></a>
            <a href="#/products/edible-oils" className="link">All edible oils <Arrow/></a>
          </div>
        </div>
      </section>

      {/* Image band — what we move */}
      <section className="image-band">
        {[
          { key:"port-cranes-dusk",   label:"Port operations", caption:"Mombasa · Dar es Salaam discharge windows" },
          { key:"loading-grain",      label:"Bulk loading",    caption:"Black Sea grain terminals" },
          { key:"container-stacks",   label:"Containerised",   caption:"Bagged fertilizer · processed food" },
          { key:"timber-stack",       label:"Forest products", caption:"Plywood · OSB · sawn softwood" },
        ].map(t => (
          <figure key={t.key} className="image-band__tile" style={{backgroundImage: `url(${window.SarpahImg.urlFor(t.key, 900, 70)})`}}>
            <figcaption>
              <div className="image-band__label">{t.label}</div>
              <div className="image-band__caption">{t.caption}</div>
            </figcaption>
          </figure>
        ))}
      </section>

      {/* Compliance + insights two-up */}
      <section className="section section--paper-2">
        <div className="container-wide" style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56}}>
          <div>
            <div className="ribbon">Compliance & settlement</div>
            <h2 className="display" style={{fontSize: "var(--t-3xl)", marginTop: 12, marginBottom: 24}}>The standards we work to.</h2>
            <ul style={{listStyle: "none", padding: 0, margin: 0}}>
              {[
                ["ICC URDG 758", "Demand guarantees — bid bonds, performance, advance-payment.", "/compliance/urdg-758"],
                ["ICC UCP 600", "Documentary credits & ISBP 821 examination practice.", "/compliance/ucp-600"],
                ["KEBS PVoC", "Pre-export verification, Routes A/B/C — 2026–2029 cycle.", "/compliance/kebs-pvoc"],
                ["KRA & EAC CET", "Customs, iCMS, four-band CET 2022.", "/compliance/kra-customs-eac-cet"],
                ["FAFB Cap 345", "Kenya fertilizer regulatory framework.", "/compliance/fafb"],
              ].map(([t, d, slug]) => (
                <li key={slug} style={{borderTop: "1px solid var(--rule)", padding: "18px 0"}}>
                  <a href={"#" + slug} style={{display: "grid", gridTemplateColumns: "1fr auto", gap: 12, alignItems: "baseline"}}>
                    <div>
                      <div style={{fontFamily:"var(--serif)", fontSize:"var(--t-lg)", marginBottom: 4}}>{t}</div>
                      <div style={{color:"var(--ink-3)", fontSize:"var(--t-sm)"}}>{d}</div>
                    </div>
                    <Arrow/>
                  </a>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <div className="ribbon">Field notes</div>
            <h2 className="display" style={{fontSize: "var(--t-3xl)", marginTop: 12, marginBottom: 24}}>What we are watching.</h2>
            <div style={{display: "grid", gap: 12}}>
              {window.SARPAH_ROUTES.filter(r => r.section === "insights").map(r => (
                <a key={r.slug} href={"#" + r.slug} className="card" style={{minHeight: "auto", padding: 24}}>
                  <span className="tag tag--accent">Insight</span>
                  <h4 className="card__title" style={{fontSize:"var(--t-lg)"}}>{r.title}</h4>
                  <p className="card__desc">{r.description}</p>
                  <div className="card__foot"><span>Read</span> <Arrow/></div>
                </a>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="section--loose">
        <div className="container">
          <div style={{textAlign: "center"}}>
            <div className="ribbon" style={{justifyContent: "center"}}>Open a working file</div>
            <h2 className="display" style={{fontSize: "var(--t-5xl)", margin: "16px auto 32px", maxWidth: "20ch"}}>
              Tell us what you’re moving. We’ll route it.
            </h2>
            <div style={{display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap"}}>
              <a href="#/talk/buyer" className="btn btn--lg btn--accent">Buyer enquiry <Arrow/></a>
              <a href="#/talk/mandate" className="btn btn--lg btn--ghost">Mandate enquiry <Arrow/></a>
              <a href="#/talk/sub-agent" className="btn btn--lg btn--ghost">Sub-agent application <Arrow/></a>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

const Arrow = S.Arrow;

window.SarpahPages = window.SarpahPages || {};
Object.assign(window.SarpahPages, {
  MarkdownPage, Home, PageHead, SectionNav, Crumbs, buildTrail
});
