/* Faderhead – Signal/Broadcast direction
   Shared chrome: atmosphere wrappers, top nav, footer, newsletter, helpers.
   All pages import these. */

/* global React */
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

/* ============ Router (lifted to App, passed via context) ============ */
const NavCtx = createContext({ route: { name: "home" }, go: () => {} });
const useNav = () => useContext(NavCtx);

/* ============ Page chrome ============ */

/* ============ Top broadcast bar ============ */
function BroadcastBar({ compact }) {
  // Top broadcast bar removed per request – render nothing.
  return null;
  /* eslint-disable no-unreachable */
  const [time, setTime] = useState(formatTime());
  useEffect(() => {
    const id = setInterval(() => setTime(formatTime()), 30000);
    return () => clearInterval(id);
  }, []);
  if (compact) {
    return (
      <div className="sig-broadcast compact mono">
        <span><span className="sig-led on" /> ON AIR</span>
        <span>{time}</span>
        <span>▮▮▮▮</span>
      </div>);

  }
  return (
    <div className="sig-broadcast mono">
      <span className="sig-bx"><span className="sig-led on" /> TRANSMITTING</span>
      <span className="sig-bx">⌁ FH·BROADCAST · 026</span>
      <span className="sig-bx">{time}</span>
      <span className="sig-bx">SIGNAL · 4 BARS ▮▮▮▮</span>
    </div>);

}
function formatTime() {
  const d = new Date();
  const pad = (n) => String(n).padStart(2, "0");
  const day = d.toLocaleDateString("en-GB").replace(/\//g, ".");
  return `${day.slice(0, 5)} · ${pad(d.getHours())}:${pad(d.getMinutes())} CET`;
}

/* ============ TopNav – appears on every non-home page ============ */
function TopNav({ compact, crumb }) {
  const { route, go } = useNav();
  const routeIdToPath = (id) => {
    const map = { music: "/music", shows: "/shows", blog: "/blog", "deep-dive": "/about", contact: "/contact" };
    return map[id] || "/";
  };
  const links = [
  { id: "music", label: "MUSIC" },
  { id: "shows", label: "SHOWS" },
  { id: "blog", label: "BLOG & PODCAST" },
  { id: "deep-dive", label: "ABOUT" },
  { id: "contact", label: "CONTACT" }];
  const extLinks = [
  { label: "MERCH ↗", href: "http://faderhead.myshopify.com" },
  { label: "PATREON ↗", href: "http://patreon.com/faderhead" }];

  return (
    <nav className={`sig-topnav mono${compact ? " compact" : ""}`}>
      <a href="/" className="sig-topnav-back"
        onClick={(e) => { e.preventDefault(); go({ name: "home" }); }}>
        ← FADERHEAD
      </a>
      {!compact &&
      <div className="sig-topnav-links">
          {links.map((l) =>
        <a key={l.id} href={routeIdToPath(l.id)}
        className={`sig-topnav-link${routeMatches(route, l.id) ? " active" : ""}`}
        onClick={(e) => { e.preventDefault(); go({ name: l.id }); }}>
              {l.label}
            </a>
        )}
          {extLinks.map((l) =>
        <a key={l.label} className="sig-topnav-link"
        href={l.href} target="_blank" rel="noopener noreferrer">{l.label}</a>
        )}
        </div>
      }
      {crumb && <span className="sig-topnav-crumb">{crumb}</span>}
    </nav>);

}
function routeMatches(route, id) {
  if (id === "music") return ["music", "discography", "album"].includes(route.name);
  return route.name === id;
}

/* ============ Newsletter (re-used everywhere) ============ */
const ML_FORM_URL = "https://assets.mailerlite.com/jsonp/952222/forms/189271061357921343/subscribe";

function NewsletterSignal({ compact, title, blurb }) {
  const [name, setName]     = useState("");
  const [email, setEmail]   = useState("");
  const [status, setStatus] = useState("idle"); // idle | loading | success | error

  async function handleSubmit(e) {
    e.preventDefault();
    if (!email) return;
    setStatus("loading");
    const body = new URLSearchParams();
    body.append("fields[email]", email);
    if (name.trim()) body.append("fields[name]", name.trim());
    body.append("ml-submit", "1");
    body.append("anticsrf", "true");
    try {
      await fetch(ML_FORM_URL, { method: "POST", body, mode: "no-cors" });
      setStatus("success");
    } catch (_) {
      setStatus("error");
    }
  }

  return (
    <section className={`sig-news${compact ? " compact" : ""}`}>
      <div className="sig-news-frame">
        <div className="sig-news-corner tl" />
        <div className="sig-news-corner tr" />
        <div className="sig-news-corner bl" />
        <div className="sig-news-corner br" />
        <div className="sig-news-head mono">
          <span>{title || "SIGN UP"}</span>
          <span className="sig-news-head-r">
              <span className={`sig-led ${status === "success" ? "on" : "on"}`} />
              {status === "success" ? "SUBSCRIBED" : status === "loading" ? "SENDING…" : "READY"}
            </span>
        </div>
        <h2 className="sig-news-title glow-teal" style={{ fontSize: "40px" }}>JOIN MY FREE NEWSLETTER</h2>
        <p className="sig-news-blurb mono">
          {blurb || <>ONE EMAIL. ONCE A MONTH.<br />New music, behind-the-scenes stories &amp; live dates.<br />Plus: blunt writing on art, the music business and the forces shaping modern life.</>}
        </p>
        {status === "success" ? (
          <div className="sig-news-success mono">
            <span className="sig-news-ok">✓ YOU'RE IN.</span>
            <p>Check your inbox for a confirmation email.</p>
          </div>
        ) : (
          <form className="sig-news-form stacked mono" onSubmit={handleSubmit}>
            <div className="sig-news-field">
              <span className="sig-news-prompt">&gt;_</span>
              <input type="text" placeholder="name (optional)" value={name}
                onChange={(e) => setName(e.target.value)} disabled={status === "loading"} />
            </div>
            <div className="sig-news-field">
              <span className="sig-news-prompt">&gt;_</span>
              <input type="email" placeholder="email" value={email} required
                onChange={(e) => setEmail(e.target.value)} disabled={status === "loading"} />
            </div>
            {status === "error" && (
              <p className="sig-news-error mono">// something went wrong — please try again.</p>
            )}
            <button type="submit" disabled={status === "loading"}>
              {status === "loading" ? "SENDING…" : "SUBSCRIBE →"}
            </button>
          </form>
        )}

        <div className="sig-news-testi">
          <blockquote>
            <p>“One of the few newsletters I actually read instead of archive!”</p>
            <cite>— Laura Jennings</cite>
          </blockquote>
          <blockquote>
            <p>“Came for the music, stayed for the writing.”</p>
            <cite>— OctoBot</cite>
          </blockquote>
          <blockquote>
            <p>“Feels more personal than social media ever does.”</p>
            <cite>— Stefan Wittler</cite>
          </blockquote>
        </div>
      </div>
    </section>);

}

/* ============ Footer ============ */
function FooterSignal({ compact }) {
  const { go } = useNav();
  return (
    <footer className={`sig-foot mono${compact ? " compact" : ""}`}>
      <div className="sig-foot-grid">
        <div>
          <div className="sig-foot-h">// social</div>
          {compact ?
          <SocialIcons /> :
          <SocialIcons />
          }
        </div>
        <div>
          <div className="sig-foot-h">// pages</div>
          <div className="sig-foot-links">
            <a className="link" href="/contact" onClick={(e) => { e.preventDefault(); go({ name: "contact" }); }}>contact</a>
            <a className="link" href="https://sync.faderhead.com" target="_blank" rel="noopener noreferrer">sync ↗</a>
            <a className="link" href="/impressum" onClick={(e) => { e.preventDefault(); go({ name: "impressum" }); }}>impressum</a>
            <a className="link" href="/datenschutz" onClick={(e) => { e.preventDefault(); go({ name: "datenschutz" }); }}>datenschutz</a>
            <a className="link" href="/shop" onClick={(e) => { e.preventDefault(); go({ name: "shop-legal" }); }}>shop</a>
          </div>
        </div>
      </div>
      <div className="sig-foot-base">
        <span style={{ textAlign: "center" }}>© 2006–2026 faderhead / not a robot records</span>
        <span style={{ textAlign: "center" }}>build v4.0 · 26.05.26</span>
      </div>
    </footer>);

}

/* ============ Reusable bits ============ */
function Led({ kind = "on" }) {
  return <span className={`sig-led ${kind}`} />;
}

function CountdownBlock({ days = 165, hours = 9, mins = 42, compact }) {
  return (
    <div className={`sig-countdown mono${compact ? " compact" : ""}`}>
      <span><b>{String(days).padStart(3, "0")}</b>d</span>
      <span><b>{String(hours).padStart(2, "0")}</b>h</span>
      <span><b>{String(mins).padStart(2, "0")}</b>m</span>
    </div>);

}

/* ============ Mobile header + slide-down menu ============ */
const SOCIALS = [
{ name: "Instagram", url: "https://www.instagram.com/faderhead_official" },
{ name: "Facebook",  url: "https://www.facebook.com/faderhead" },
{ name: "YouTube",   url: "https://www.youtube.com/faderhead" },
{ name: "TikTok",    url: "https://www.tiktok.com/@faderhead" },
{ name: "WhatsApp",  url: "https://whatsapp.com/channel/0029VaVdeQ7L7UVbnaqrru3V" }];

function SocialIcon({ name }) {
  const s = { width: "18", height: "18", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true" };
  if (name === "Instagram") return (
    <svg {...s} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="2" width="20" height="20" rx="5" />
      <circle cx="12" cy="12" r="5" />
      <circle cx="17.5" cy="6.5" r="1.2" fill="currentColor" stroke="none" />
    </svg>);
  if (name === "Facebook") return (
    <svg {...s}><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" /></svg>);
  if (name === "YouTube") return (
    <svg {...s}>
      <path d="M22.54 6.42a2.78 2.78 0 0 0-1.95-1.95C18.88 4 12 4 12 4s-6.88 0-8.59.47a2.78 2.78 0 0 0-1.95 1.95A29 29 0 0 0 1 12a29 29 0 0 0 .46 5.58A2.78 2.78 0 0 0 3.41 19.53C5.12 20 12 20 12 20s6.88 0 8.59-.47a2.78 2.78 0 0 0 1.95-1.95A29 29 0 0 0 23 12a29 29 0 0 0-.46-5.58z" />
      <polygon points="9.75 15.02 15.5 12 9.75 8.98 9.75 15.02" style={{ fill: "var(--bg, #08080c)" }} />
    </svg>);
  if (name === "TikTok") return (
    <svg {...s}><path d="M12.53.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z" /></svg>);
  if (name === "WhatsApp") return (
    <svg {...s}><path d="M17.47 14.38c-.3-.15-1.76-.87-2.03-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.94 1.16-.17.2-.35.22-.64.07-.3-.15-1.26-.46-2.39-1.48-.88-.79-1.48-1.76-1.65-2.06-.17-.3-.02-.46.13-.6.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.67-1.61-.92-2.21-.24-.58-.49-.5-.67-.51-.17-.01-.37-.01-.57-.01-.2 0-.52.07-.79.37-.27.3-1.04 1.02-1.04 2.48 0 1.46 1.07 2.88 1.21 3.07.15.2 2.1 3.2 5.08 4.49.71.31 1.26.49 1.69.63.71.23 1.36.2 1.87.12.57-.09 1.76-.72 2.01-1.41.25-.7.25-1.29.17-1.41-.07-.12-.27-.2-.57-.35m-5.42 7.4h-.004a9.87 9.87 0 0 1-5.03-1.38l-.36-.21-3.74.98 1-3.65-.24-.37a9.86 9.86 0 0 1-1.51-5.26C2.16 6.44 6.6 2 12.05 2c2.64 0 5.12 1.03 6.99 2.9a9.82 9.82 0 0 1 2.89 6.99c-.003 5.45-4.44 9.88-9.88 9.88m8.41-18.3A11.82 11.82 0 0 0 12.05 0C5.5 0 .16 5.34.16 11.89c0 2.1.55 4.14 1.59 5.95L.06 24l6.3-1.65a11.88 11.88 0 0 0 5.68 1.45h.005c6.55 0 11.89-5.34 11.89-11.89a11.82 11.82 0 0 0-3.48-8.41z" /></svg>);
  return <span>{name[0]}</span>;
}

function SocialIcons({ lg }) {
  return (
    <div className={`sig-socials${lg ? " lg" : ""}`}>
      {SOCIALS.map((s) =>
      <a key={s.name} href={s.url} className="sig-social" aria-label={s.name} title={s.name}
      target="_blank" rel="noopener noreferrer"><SocialIcon name={s.name} /></a>
      )}
    </div>);
}

const MOBILE_MENU = [
{ label: "MUSIC", route: { name: "music" } },
{ label: "SHOWS", route: { name: "shows" } },
{ label: "MERCH", ext: true, href: "http://faderhead.myshopify.com" },
{ label: "BLOG · PODCAST", route: { name: "blog" } },
{ label: "ABOUT", route: { name: "deep-dive" } },
{ label: "CONTACT", route: { name: "contact" } },
{ label: "THE INNER CIRCLE", ext: true, href: "http://patreon.com/faderhead" }];

function SigMobileNav({ route, go, open, setOpen }) {
  const nav = (r) => {setOpen(false);if (r) go(r);};
  return (
    <>
      <header className={`sig-mhead mono${open ? " open" : ""}`}>
        <button className="sig-mhead-mark" onClick={() => nav({ name: "home" })}>FADERHEAD.COM</button>
        <button className="sig-mhead-burger" aria-label="menu" aria-expanded={open}
        onClick={() => setOpen((o) => !o)}>
          <span /><span /><span />
        </button>
      </header>
      {open &&
      <nav className="sig-mmenu mono">
          {MOBILE_MENU.map((it, i) => {
          const active = it.route && (routeMatches(route, it.route.name) || route.name === it.route.name);
            const routePathMap = { music: "/music", shows: "/shows", blog: "/blog", "deep-dive": "/about", contact: "/contact" };
          const href = it.ext ? it.href : (it.route ? (routePathMap[it.route.name] || "/") : "/");
          return (
            <a key={it.label} href={href}
              className={active ? "active" : ""}
              target={it.ext ? "_blank" : undefined}
              rel={it.ext ? "noopener noreferrer" : undefined}
              onClick={(e) => { if (!it.ext) { e.preventDefault(); setOpen(false); if (it.route) go(it.route); } else { setOpen(false); } }}>
                <span className="sig-mmenu-label">{it.label}{it.ext && <span className="sig-mmenu-ext"> ↗</span>}</span>
                <span className="sig-mmenu-num">{String(i + 1).padStart(2, "0")}</span>
              </a>);

        })}
          <div className="sig-mmenu-social">
            <div className="sig-mmenu-social-h mono">// follow on socials
</div>
            <SocialIcons lg />
          </div>
        </nav>}
    </>);

}

window.BroadcastBar = BroadcastBar;
window.TopNav = TopNav;
window.NewsletterSignal = NewsletterSignal;
window.FooterSignal = FooterSignal;
window.NavCtx = NavCtx;
window.useNav = useNav;
window.Led = Led;
window.CountdownBlock = CountdownBlock;
window.SigMobileNav = SigMobileNav;
window.SocialIcons = SocialIcons;