/* global React */

/* Social — JT's Instagram doubles as the network's for now; the rest are
   the network accounts. YouTube intentionally omitted until it's set up. */
const HOWTO_SOCIALS = [
  {
    label: "Instagram (Network)",
    handle: "@the.howto.network",
    href: "https://www.instagram.com/the.howto.network",
    path: "M12 2.16c3.2 0 3.58.01 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.7 3.7 0 0 1-1.38-.9 3.7 3.7 0 0 1-.9-1.38c-.16-.42-.36-1.06-.41-2.23-.06-1.27-.07-1.65-.07-4.85s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41C8.42 2.17 8.8 2.16 12 2.16M12 0C8.74 0 8.33.01 7.05.07 5.78.13 4.9.33 4.14.63c-.79.3-1.46.72-2.12 1.38C1.35 2.68.93 3.35.63 4.14.33 4.9.13 5.78.07 7.05.01 8.33 0 8.74 0 12s.01 3.67.07 4.95c.06 1.27.26 2.15.56 2.91.3.79.72 1.46 1.38 2.12.66.66 1.33 1.08 2.12 1.38.76.3 1.64.5 2.91.56C8.33 23.99 8.74 24 12 24s3.67-.01 4.95-.07c1.27-.06 2.15-.26 2.91-.56a5.86 5.86 0 0 0 2.12-1.38 5.86 5.86 0 0 0 1.38-2.12c.3-.76.5-1.64.56-2.91.06-1.28.07-1.69.07-4.95s-.01-3.67-.07-4.95c-.06-1.27-.26-2.15-.56-2.91a5.86 5.86 0 0 0-1.38-2.12A5.86 5.86 0 0 0 19.86.63c-.76-.3-1.64-.5-2.91-.56C15.67.01 15.26 0 12 0zm0 5.84a6.16 6.16 0 1 0 0 12.32 6.16 6.16 0 0 0 0-12.32zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.41-10.85a1.44 1.44 0 1 0 0 2.88 1.44 1.44 0 0 0 0-2.88z",
  },
  {
    label: "Instagram (JT)",
    handle: "@becoming.jt",
    href: "https://www.instagram.com/becoming.jt",
    path: "M12 2.16c3.2 0 3.58.01 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.7 3.7 0 0 1-1.38-.9 3.7 3.7 0 0 1-.9-1.38c-.16-.42-.36-1.06-.41-2.23-.06-1.27-.07-1.65-.07-4.85s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41C8.42 2.17 8.8 2.16 12 2.16M12 0C8.74 0 8.33.01 7.05.07 5.78.13 4.9.33 4.14.63c-.79.3-1.46.72-2.12 1.38C1.35 2.68.93 3.35.63 4.14.33 4.9.13 5.78.07 7.05.01 8.33 0 8.74 0 12s.01 3.67.07 4.95c.06 1.27.26 2.15.56 2.91.3.79.72 1.46 1.38 2.12.66.66 1.33 1.08 2.12 1.38.76.3 1.64.5 2.91.56C8.33 23.99 8.74 24 12 24s3.67-.01 4.95-.07c1.27-.06 2.15-.26 2.91-.56a5.86 5.86 0 0 0 2.12-1.38 5.86 5.86 0 0 0 1.38-2.12c.3-.76.5-1.64.56-2.91.06-1.28.07-1.69.07-4.95s-.01-3.67-.07-4.95c-.06-1.27-.26-2.15-.56-2.91a5.86 5.86 0 0 0-1.38-2.12A5.86 5.86 0 0 0 19.86.63c-.76-.3-1.64-.5-2.91-.56C15.67.01 15.26 0 12 0zm0 5.84a6.16 6.16 0 1 0 0 12.32 6.16 6.16 0 0 0 0-12.32zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.41-10.85a1.44 1.44 0 1 0 0 2.88 1.44 1.44 0 0 0 0-2.88z",
  },
  {
    label: "TikTok",
    handle: "@the.how.to.networ",
    href: "https://www.tiktok.com/@the.how.to.networ",
    path: "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",
  },
  {
    label: "Twitter / X",
    handle: "@howto_network_",
    href: "https://x.com/howto_network_",
    path: "M18.244 2.25h3.308l-7.227 8.26 8.502 11.24h-6.66l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231zm-1.161 17.52h1.833L7.084 4.126H5.117l11.966 15.644z",
  },
  {
    label: "Facebook",
    handle: "thehowtonetwork",
    href: "https://www.facebook.com/thehowtonetwork",
    path: "M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z",
  },
  {
    label: "Pinterest",
    handle: "thehowtonetwork",
    href: "https://www.pinterest.com/thehowtonetwork",
    path: "M12 0C5.373 0 0 5.372 0 12c0 5.084 3.163 9.426 7.627 11.174-.105-.949-.2-2.405.042-3.441.218-.937 1.407-5.965 1.407-5.965s-.359-.719-.359-1.782c0-1.668.967-2.914 2.171-2.914 1.023 0 1.518.769 1.518 1.69 0 1.029-.655 2.568-.994 3.995-.283 1.194.599 2.169 1.777 2.169 2.133 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.012-4.882-3.414 0-5.418 2.561-5.418 5.207 0 1.031.397 2.138.893 2.738a.36.36 0 0 1 .083.345c-.091.378-.293 1.194-.333 1.361-.052.22-.174.266-.401.16-1.499-.698-2.436-2.889-2.436-4.649 0-3.785 2.75-7.262 7.929-7.262 4.163 0 7.398 2.967 7.398 6.931 0 4.136-2.608 7.464-6.227 7.464-1.216 0-2.359-.632-2.75-1.378l-.748 2.853c-.271 1.043-1.002 2.35-1.492 3.146C9.57 23.812 10.763 24 12 24c6.627 0 12-5.373 12-12 0-6.628-5.373-12-12-12z",
  },
];

const SOCIAL_CSS = `
.howto-social { display:flex; align-items:center; gap:12px; flex-wrap:wrap; margin-top:28px; padding-top:24px; border-top:1px solid var(--rule); }
.howto-social .howto-social-label { font-family:var(--f-mono); font-size:10px; letter-spacing:.24em; text-transform:uppercase; color:var(--ink-mute); margin-right:6px; }
.howto-social a { display:inline-flex; align-items:center; justify-content:center; width:38px; height:38px; border:1px solid var(--rule-strong); border-radius:999px; color:var(--ink-mute); transition:color .2s, border-color .2s, transform .2s; }
.howto-social a:hover { color:var(--accent); border-color:var(--accent); transform:translateY(-2px); }
.howto-social svg { width:17px; height:17px; fill:currentColor; display:block; }
`;

const HOWTO_EDITIONS = [
  { label: "HowTo: Home Edition", href: "https://howtohomeedition.com" },
  { label: "HowTo: Food Edition", href: "https://howtofoodedition.com" },
  { label: "HowTo: Beauty Edition", href: "https://howtobeautyedition.com" },
  { label: "HowTo: Travel Edition", href: "https://howtotraveledition.com" },
  { label: "HowTo: Tech Edition", href: "https://howtotechedition.com" },
  { label: "HowTo: Family Edition", href: "https://howtofamilyedition.com" },
  { label: "HowTo: Finance Edition", href: "https://howtofinanceedition.com" },
  { label: "HowTo: Fashion Edition", href: "https://howtofashionedition.com" },
  { label: "HowTo: Health & Fitness Edition", href: "/en/" },
];

/* Community workouts strip — renders only on L4 content leaves, just above the
   footer. Reader-submitted workouts for this page + Save/Share. Self-gating so it
   never appears on the home, hubs, or non-content pages. */
const CW_HEALTH_REST = "https://txxeefepmwqfptlzfxkf.supabase.co";
const CW_HEALTH_PUB = "sb_publishable_ziRn1I6oEYiUfLVdxvzmbw_AShSqb7Z";
const CW_SHARED_REST = "https://qdbalscnmljbgdkrfqsy.supabase.co";
const CW_SHARED_PUB = "sb_publishable_YBYSc0pXi4B8JuUgCPIGeg_LM-cTc1Z";
const CW_AUTH_TOKEN_KEY = "sb-qdbalscnmljbgdkrfqsy-auth-token";

const CW_STRIP_CSS = `
.cw-strip{max-width:1100px;margin:0 auto;padding:clamp(40px,6vw,72px) clamp(20px,5vw,40px) 8px}
.cw-strip-badge{display:inline-flex;align-items:center;gap:8px;font-family:var(--f-mono,monospace);font-size:11px;letter-spacing:.2em;text-transform:uppercase;font-weight:600;color:#6b8a7a}
.cw-strip-badge::before{content:"";width:7px;height:7px;border-radius:50%;background:#6b8a7a}
.cw-strip h2{font-family:var(--f-display,Georgia,serif);font-size:clamp(22px,3vw,30px);font-weight:500;margin:10px 0 18px;letter-spacing:-.01em}
.cw-strip-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:14px}
.cw-strip-card{display:block;border:1px solid rgba(128,128,128,.28);border-radius:12px;overflow:hidden;text-decoration:none;color:inherit;transition:transform .12s,border-color .12s}
.cw-strip-card:hover{transform:translateY(-2px);border-color:#6b8a7a}
.cw-strip-card .ph{aspect-ratio:16/10;width:100%;display:block;object-fit:cover;background:linear-gradient(135deg,rgba(107,138,122,.18),rgba(128,128,128,.10))}
.cw-strip-card .bd{padding:12px 14px}
.cw-strip-card .t{font-family:var(--f-display,Georgia,serif);font-size:16px;font-weight:600;line-height:1.2;margin-bottom:4px}
.cw-strip-card .m{font-size:12px;opacity:.62}
.cw-strip-actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:18px}
.cw-strip-actions button,.cw-strip-actions a.cw-add{font-family:var(--f-sans,sans-serif);font-size:13px;font-weight:600;padding:9px 18px;border-radius:999px;border:1px solid rgba(128,128,128,.34);background:transparent;color:inherit;cursor:pointer;text-decoration:none}
.cw-strip-actions a.cw-add{border-style:dashed;color:#6b8a7a;border-color:#9bb0a4}
.cw-strip-actions button:hover,.cw-strip-actions a.cw-add:hover{border-color:#6b8a7a}
`;

function cwSession() { try { const r = JSON.parse(localStorage.getItem(CW_AUTH_TOKEN_KEY) || "null"); return r && r.access_token ? r : null; } catch { return null; } }
function cwJwtSub(t) { try { return JSON.parse(atob(t.split(".")[1])).sub; } catch { return null; } }

function CommunityLeafStrip() {
  const [rows, setRows] = React.useState(null);
  const [saveLabel, setSaveLabel] = React.useState("♡ Save");
  const [shareLabel, setShareLabel] = React.useState("↗ Share");

  // Gate: only L4 content leaves under /en/{health|fitness}/.../  (4+ segments).
  let path = typeof location !== "undefined" ? location.pathname : "";
  if (path && !path.endsWith("/")) path += "/";
  const seg = path.split("/").filter(Boolean);
  const isLeaf = seg.length >= 4 && /^[a-z]{2}$/.test(seg[0]) && (seg[1] === "health" || seg[1] === "fitness");

  React.useEffect(() => {
    if (!isLeaf) return;
    const q = `${CW_HEALTH_REST}/rest/v1/community_workouts?parent_leaf_slug=eq.${encodeURIComponent(path)}&status=eq.approved&select=slug,title,cover_url,author_username,duration_min&order=created_at.desc&limit=8`;
    fetch(q, { headers: { apikey: CW_HEALTH_PUB, authorization: `Bearer ${CW_HEALTH_PUB}` } })
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setRows(Array.isArray(d) ? d : []))
      .catch(() => setRows([]));
  }, [isLeaf, path]);

  if (!isLeaf) return null;

  async function onSave() {
    const s = cwSession();
    if (!s) { location.href = `/signin.html?next=${encodeURIComponent(path)}`; return; }
    setSaveLabel("Saving…");
    try {
      await fetch(`${CW_SHARED_REST}/rest/v1/saved_guides`, {
        method: "POST",
        headers: { apikey: CW_SHARED_PUB, Authorization: `Bearer ${s.access_token}`, "Content-Type": "application/json", Prefer: "resolution=merge-duplicates,return=minimal" },
        body: JSON.stringify({ user_id: cwJwtSub(s.access_token), page_slug: path, edition: "health", title: document.title.replace(/ [—-].*$/, "") }),
      });
      setSaveLabel("♥ Saved");
    } catch { setSaveLabel("♡ Save"); }
  }
  async function onShare() {
    const url = location.href, title = document.title;
    if (navigator.share) { try { await navigator.share({ title, url }); return; } catch {} }
    try { await navigator.clipboard.writeText(url); setShareLabel("Link copied"); } catch {}
  }

  const hasRows = rows && rows.length > 0;
  return (
    <section className="cw-strip" aria-label="Community workouts">
      <style dangerouslySetInnerHTML={{ __html: CW_STRIP_CSS }} />
      <span className="cw-strip-badge">From the community</span>
      <h2>{hasRows ? "Workouts readers shared" : "Got a routine for this?"}</h2>
      {hasRows && (
        <div className="cw-strip-grid">
          {rows.map((w) => (
            <a className="cw-strip-card" key={w.slug} href={`/workout/${w.slug}`}>
              {w.cover_url ? <img className="ph" src={w.cover_url} alt="" loading="lazy" /> : <span className="ph" />}
              <div className="bd">
                <div className="t">{w.title}</div>
                <div className="m">{[w.duration_min ? `${w.duration_min} min` : "", w.author_username ? `@${w.author_username}` : ""].filter(Boolean).join(" · ")}</div>
              </div>
            </a>
          ))}
        </div>
      )}
      <div className="cw-strip-actions">
        <a className="cw-add" href={`/create?parent=${encodeURIComponent(path)}`}>+ Share your workout</a>
        <button type="button" onClick={onSave}>{saveLabel}</button>
        <button type="button" onClick={onShare}>{shareLabel}</button>
      </div>
    </section>
  );
}

function HowToFooter({ screenLabel = "Footer" }) {
  const assetBase = window.HOWTO_ASSET_BASE || "";
  const [email, setEmail] = React.useState("");
  const [status, setStatus] = React.useState("idle");

  async function handleSubscribe(event) {
    event.preventDefault();
    if (!email || status === "loading") return;

    setStatus("loading");
    try {
      const response = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      if (!response.ok) throw new Error("Subscribe failed");
      setStatus("success");
    } catch {
      setStatus("error");
    }
  }

  return (
    <React.Fragment>
    <CommunityLeafStrip />
    <footer className="footer footer-network" data-screen-label={screenLabel}>
      <div className="footer-inner">
        <div className="footer-network-top">
          <div className="footer-brand">
            <div className="footer-brand-lockup">
              <img src={`${assetBase}assets/brand/favicon.png`} alt="HowTo Health Edition logo" />
              <div>
                <span>How To:</span>
                <strong>Health &amp; Fitness Edition</strong>
              </div>
            </div>
            <p>A plain-spoken health and fitness magazine for training, food, recovery, care, and everyday wellness.</p>
          </div>

          <div className="footer-col footer-editions">
            <h4>Other Editions</h4>
            <ul>
              {HOWTO_EDITIONS.map((edition) => (
                <li key={edition.label}>
                  <a href={edition.href}>{edition.label}</a>
                </li>
              ))}
            </ul>
          </div>

          <div className="footer-col footer-sub">
            <h4>Newsletter</h4>
            <p>The Health &amp; Fitness Letter is where the week gets edited down.</p>
            {status === "success" ? (
              <p className="footer-sub-success" role="status">You're in.</p>
            ) : (
              <form className="footer-sub-form" onSubmit={handleSubscribe}>
                <div className="footer-sub-input">
                  <input
                    type="email"
                    value={email}
                    onChange={(event) => setEmail(event.target.value)}
                    placeholder="you@somewhere.com"
                    aria-label="Email address"
                    aria-describedby={status === "error" ? "newsletter-error" : undefined}
                    required
                  />
                  <button type="submit" disabled={status === "loading"}>
                    {status === "loading" ? "Signing up" : "Sign up"}
                  </button>
                </div>
                {status === "error" && (
                  <p className="footer-sub-error" id="newsletter-error" role="alert">Something went wrong. Try again.</p>
                )}
              </form>
            )}
          </div>

          <div className="footer-col">
            <h4>The Edition</h4>
            <ul>
              <li><a href="/en/about/">About</a></li>
              <li><a href="/en/contact/">Contact</a></li>
              <li><a href="/en/#contributors">Contributors</a></li>
              <li><a href="/en/#letter">Editor's Letter</a></li>
            </ul>
          </div>
        </div>

        <style dangerouslySetInnerHTML={{ __html: SOCIAL_CSS }} />
        <div className="howto-social">
          <span className="howto-social-label">Follow</span>
          {HOWTO_SOCIALS.map((s) => (
            <a
              key={s.label}
              href={s.href}
              target="_blank"
              rel="noopener noreferrer"
              aria-label={`${s.label} — ${s.handle}`}
              title={`${s.label} · ${s.handle}`}
            >
              <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                <path d={s.path} />
              </svg>
            </a>
          ))}
        </div>

        <div className="footer-legal-row">
          <ul>
            <li><a href="/en/privacy/">Privacy</a></li>
            <li><a href="/en/terms/">Terms</a></li>
            <li><a href="/en/disclaimer/">Disclaimer</a></li>
            <li><a href="/en/accessibility/">Accessibility</a></li>
            <li><a href="mailto:hello@thehowtonetwork.com">hello@thehowtonetwork.com</a></li>
          </ul>
        </div>

        <div className="footer-disclaimer">
          <h4>Disclaimer</h4>
          <div className="footer-disclaimer-grid">
            <p>
              Content on this site is for general information only. It may not reflect current codes, regulations, professional standards, or the needs of your body.
            </p>
            <p>
              HowTo: Health &amp; Fitness provides general wellness and movement guidance only. Not medical advice. Consult a qualified professional before changing anything that affects your health.
            </p>
          </div>
        </div>

        <div className="footer-bottom">
          <span>© 2026 HowTo: Health &amp; Fitness Edition. All rights reserved.</span>
          <span>Part of the HowTo Network - thehowtonetwork.com</span>
        </div>
      </div>
    </footer>
    </React.Fragment>
  );
}

window.HowToFooter = HowToFooter;
window.Footer = HowToFooter;
