/* Chrome — Nav, AudienceStrip, Footer.
   These render once around whatever page the router shows.

   Per CTO Domain 2 remediation (WO-2026-05-27-marketing-site-remediation):
   - The BrowserChrome SPA URL-bar mock has been removed. It was a mockup-only
     affectation that read as broken pre-launch chrome on a real preview link
     and hard-coded the wrong domain (solas.uk vs the canonical
     solasinsurance.co.uk per /brain/brand/state.md).
   - The wordmark is now an inline SVG (see SVG_WORDMARK.md). The previous
     live-text anchor with a background-image PNG failed open to a raw
     "solas" text node if the PNG 404'd — directly breaching the
     tokens.css "Never write 'solas' as visible text" rule.
   - The footer regulatory line now reads from siteConfig (pre-authorisation
     neutral form), per CEP-2026-05-27-001 help-first alternative. The
     placeholder "FRN 000000" / "No. 00000000" line has been retired.
   - Form handlers no longer alert(); they log to console as a development
     stub. Alerts read as broken UX on a pre-launch preview. */

const { useState } = React;

const C = window.solasContent;

// ---- Tiny utilities --------------------------------------------------------

const cn = (...xs) => xs.filter(Boolean).join(" ");

// ---- Wordmark · inline SVG -----------------------------------------------
// Directional placeholder pending Söhne licensing per /brain/brand/state.md
// Söhne open item. The <text> element inherits font-family from the
// .solas-wordmark--svg CSS rule (currently Hanken Grotesk fallback; switches
// to Söhne Kräftig when the licensed WOFF2 lands per tokens.css). Full
// rationale + aria conventions in SVG_WORDMARK.md.
//
// The SVG is the only "solas" text node — there is no anchor-text fallback
// to leak raw "solas" text if a background image fails. The aria-label
// carries the accessible name.

const SolasWordmark = ({ size = "md", ariaLabel = "Solas home" }) => {
  // Heights match the legacy PNG-backed wordmark class scale so existing
  // layout (Nav 28px, Footer 40px etc.) is unchanged.
  const heights = { sm: 22, md: 28, lg: 40, hero: 80 };
  const h = heights[size] || heights.md;
  const w = Math.round(h * (513 / 152)); // preserve native crop ratio
  // viewBox height/width are arbitrary as long as the aspect matches;
  // we use 100/34 so the inline <text> y-baseline is easy to reason about.
  return (
    <svg
      className={cn("solas-wordmark--svg", size && `solas-wordmark--svg--${size}`)}
      role="img"
      aria-label={ariaLabel}
      width={w}
      height={h}
      viewBox="0 0 100 34"
      focusable="false"
    >
      <text
        x="0"
        y="26"
        fontFamily="inherit"
        fontWeight="600"
        fontSize="30"
        letterSpacing="-0.3"
        fill="currentColor"
      >solas</text>
    </svg>
  );
};

// ---- AudienceStrip — quiet B2B selector under the nav --------------------
// "Whose room is this?" answered explicitly. Only on the homepage.

const AudienceStrip = ({ active, onNav }) => (
  <div className="audience-strip" data-screen-label="Audience strip">
    <div className="audience-strip__lbl">{C.audienceStrip.label}</div>
    <div className="audience-strip__opts">
      {C.audienceStrip.options.map((o) => (
        <a
          key={o.key}
          href={"#" + o.href}
          className={active === o.key ? "is-active" : ""}
          onClick={(e) => { e.preventDefault(); onNav(o.href); }}
        >{o.label}</a>
      ))}
    </div>
  </div>
);

// ---- Nav — top of every page --------------------------------------------
// Wordmark left (inline SVG). Editorial links + a single Ink-Blue CTA right.
// Per the joint CCO+CLO /investors review, the nav default CTA has flipped
// from "Investor brief" → "Join the waitlist". Pointing every visitor on
// every page at a s.21 surface was operationally over-promoting the
// financial-promotion surface; the investor route is now accessible via
// the Investors nav link, not the universal CTA. When Socotra lands the
// label can update to "Request a quote".

const NAV_ITEMS = C.nav.items;

const Nav = ({ active, onNav, ctaTarget = "/quote", ctaLabel = "Join the waitlist" }) => {
  return (
    <nav className="solas-nav" data-screen-label="Nav">
      <a
        href="#/"
        className="solas-wordmark-link"
        aria-label="Solas home"
        onClick={(e) => { e.preventDefault(); onNav("/"); }}
      >
        <SolasWordmark size="md" ariaLabel="Solas home" />
      </a>
      <div className="solas-nav__links">
        {NAV_ITEMS.map((item) => (
          <a
            key={item.id}
            href={"#" + item.href}
            className={cn("solas-nav__a", active === item.id && "is-active")}
            onClick={(e) => { e.preventDefault(); onNav(item.href); }}
          >{item.label}</a>
        ))}
        <span className="solas-nav__sep" aria-hidden="true" />
        <a
          href={"#" + ctaTarget}
          className="solas-nav__cta"
          onClick={(e) => { e.preventDefault(); onNav(ctaTarget); }}
        >{ctaLabel}</a>
      </div>
    </nav>
  );
};

// ---- Social icons (kept editorial, hairline) ----------------------------

const SocialIcon = ({ kind }) => {
  const c = "solas-footer__svg";
  switch (kind) {
    case "linkedin":
      return (
        <svg className={c} width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" strokeLinejoin="miter">
          <rect x="3" y="3" width="18" height="18" />
          <line x1="7" y1="10" x2="7" y2="17" />
          <circle cx="7" cy="7.2" r="0.6" fill="currentColor" stroke="none" />
          <path d="M11 17V10 M11 12.5c0-1.4 1-2.5 2.5-2.5s2.5 1.1 2.5 2.5V17" />
        </svg>
      );
    case "substack":
      return (
        <svg className={c} width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" strokeLinejoin="miter">
          <line x1="4" y1="6" x2="20" y2="6" />
          <line x1="4" y1="10" x2="20" y2="10" />
          <path d="M4 14h16v6l-8-4-8 4z" />
        </svg>
      );
    case "rss":
      return (
        <svg className={c} width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M4 11a9 9 0 0 1 9 9" />
          <path d="M4 4a16 16 0 0 1 16 16" />
          <circle cx="5" cy="19" r="1" fill="currentColor" stroke="none" />
        </svg>
      );
    case "mail":
      return (
        <svg className={c} width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" strokeLinejoin="miter">
          <rect x="3" y="5" width="18" height="14" />
          <path d="M3 5l9 8 9-8" />
        </svg>
      );
    default:
      return null;
  }
};

// ---- Form submission stub ------------------------------------------------
// PRODUCTION pattern: zod-validate → Turnstile verify (server) → rate-limit
// → Hubspot post → Plausible event. See integrations.md.
// MOCKUP: log to console only; no UI alert (alerts read as broken pre-launch).

const stubFormSubmit = (formName) => (e) => {
  e.preventDefault();
  if (typeof console !== 'undefined') {
    console.log(
      `[Solas mockup] form submission stub — production wires to ` +
      `Hubspot Forms API per integrations.md (form: ${formName})`
    );
  }
};

// ---- Footer -------------------------------------------------------------

const Footer = ({ onNav }) => {
  const handle = (href) => (e) => { e.preventDefault(); onNav(href); };

  // Pull regulatory identity from siteConfig (the single source of truth).
  // Fallback to literal nulls if siteConfig is not loaded — the rendered
  // string then contains explicit "[pending]" markers so a missing config
  // is visible, not silently filled with placeholder zeros.
  const cfg = (typeof window !== 'undefined' && window.siteConfig) || {};
  const ch = cfg.companiesHouseNumber || '[Companies House number pending]';
  const office = cfg.registeredOffice || '[registered office pending]';
  const entity = cfg.legalEntityName || 'Solas Home Insurance Services Ltd';
  const country = cfg.registeredCountry || 'England';

  return (
    <footer className="solas-footer" data-screen-label="Footer">
      <div className="solas-footer__main">
        <div className="solas-footer__brand">
          <a
            href="#/"
            className="solas-wordmark-link solas-wordmark-link--lg"
            aria-label="Solas home"
            onClick={handle("/")}
          >
            <SolasWordmark size="lg" ariaLabel="Solas home" />
          </a>
          <p className="solas-footer__tag">
            {C.footer.tagline}
          </p>
        </div>

        <nav className="solas-footer__cols" aria-label="Footer">
          {C.footer.columns.map((col, ci) => (
            <div className="solas-footer__col" key={ci}>
              <div className="solas-footer__h">{col.heading}</div>
              {col.links.map((l, li) => (
                <a key={li} href={"#" + l.href} onClick={handle(l.href)}>{l.label}</a>
              ))}
            </div>
          ))}

          <div className="solas-footer__col solas-footer__col--keep">
            <div className="solas-footer__h">{C.footer.newsletter.heading}</div>
            <div className="solas-footer__social" role="group" aria-label="Solas elsewhere">
              <a href="https://linkedin.com/company/solas" aria-label="Solas on LinkedIn" target="_blank" rel="noreferrer"><SocialIcon kind="linkedin" /></a>
              {/* NOTE: solas.substack.com retained pending Substack-handle-canonicalisation
                  decision — flagged in tech-remediation-log.md. */}
              <a href="https://solas.substack.com" aria-label="The Solas Letter on Substack" target="_blank" rel="noreferrer"><SocialIcon kind="substack" /></a>
              <a href="/feed.xml" aria-label="RSS"><SocialIcon kind="rss" /></a>
              <a href="mailto:hello@solasinsurance.co.uk" aria-label="Email Solas"><SocialIcon kind="mail" /></a>
            </div>
            <form className="solas-footer__sub" onSubmit={stubFormSubmit("journal-signup")} data-form="journal-signup">
              <label className="solas-footer__sublbl" htmlFor="solas-footer-email">
                {C.footer.newsletter.label}
              </label>
              <div className="solas-footer__subrow">
                <input id="solas-footer-email" type="email" placeholder={C.footer.newsletter.placeholder} />
                <button type="submit" aria-label="Subscribe to the Solas Letter">→</button>
              </div>
              <p className="solas-footer__subnote">
                {C.footer.newsletter.note}
              </p>
            </form>
          </div>
        </nav>
      </div>

      {/* Footer regulatory line — pre-authorisation neutral form.
          Per CEP-2026-05-27-001 help-first alternative (no-AR-yet variant).
          The load-bearing phrase "no regulated activity is carried on
          through this site" is the s.21 financial-promotion protection
          and is NOT stylistic — do not cut it.
          When the FCA grants Part 4A authorisation, siteConfig flips
          fcaAuthorisationStatus to 'direct' + sets the real FRN, and this
          block renders the GEN 4 Annex 1R form. Until then, no FCA claim. */}
      <div className="solas-footer__legal">
        <span>
          {entity} {C.footer.legal.statusLine}
        </span>
        <span>
          Registered in {country} · No. {ch} · {office}.
        </span>
        <span>
          {C.footer.legal.copyright} ·{" "}
          <a href="#/legal" onClick={handle("/legal")}>Privacy</a> ·{" "}
          <a href="#/legal" onClick={handle("/legal")}>Cookies</a> ·{" "}
          <a href="#/legal" onClick={handle("/legal")}>Complaints</a> ·{" "}
          <a href="#/legal" onClick={handle("/legal")}>All policies</a>
        </span>
      </div>
    </footer>
  );
};

Object.assign(window, { Nav, AudienceStrip, Footer, SocialIcon, SolasWordmark, cn, stubFormSubmit });
