/* leadership.jsx — Full-bleed paper section: How I Lead · AI POV · Values */
/* global React, Bloom, Splatter, RotatingPolaroid */

const { useState: useStateLD, useEffect: useEffectLD } = React;

/* OnVelocity newsletter — pulls the most recent post live from the Substack
   RSS feed so the callout updates itself. Substack's feed sends no CORS
   header, so we read it through a public read-only proxy; on any failure we
   fall back to a static card that still links to the publication. */
const SUBSTACK_URL = "https://onvelocity.substack.com";
const SUBSTACK_FEED = "https://onvelocity.substack.com/feed";

const SUBSTACK_ICON = (
  <svg className="substack-card__mark" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
    <path d="M22.539 8.242H1.46V5.406h21.08v2.836zM1.46 10.812V24L12 18.11 22.54 24V10.812H1.46zM22.539 0H1.46v2.836h21.08V0z" />
  </svg>
);

function SubstackLatest() {
  const [post, setPost] = useStateLD(null);
  const [status, setStatus] = useStateLD("loading"); // loading | ok | error

  useEffectLD(() => {
    let cancelled = false;
    const proxied = "https://api.allorigins.win/raw?url=" + encodeURIComponent(SUBSTACK_FEED);
    fetch(proxied)
      .then((r) => { if (!r.ok) throw new Error("feed " + r.status); return r.text(); })
      .then((xml) => {
        if (cancelled) return;
        const doc = new DOMParser().parseFromString(xml, "text/xml");
        const item = doc.querySelector("item");
        if (!item) throw new Error("no items");
        const text = (sel) => (item.querySelector(sel) ? item.querySelector(sel).textContent : "").trim();
        const enc = item.querySelector("enclosure");
        setPost({
          title: text("title"),
          link: text("link") || SUBSTACK_URL,
          blurb: text("description"),
          image: enc ? enc.getAttribute("url") : "",
        });
        setStatus("ok");
      })
      .catch(() => { if (!cancelled) setStatus("error"); });
    return () => { cancelled = true; };
  }, []);

  const live = status === "ok" && post;
  const href = live ? post.link : SUBSTACK_URL;

  return (
    <a className="substack-card" href={href} target="_blank" rel="noopener noreferrer"
       data-status={status}>
      <span className="substack-card__eyebrow">
        {SUBSTACK_ICON}
        <span>Latest from <strong>OnVelocity</strong></span>
      </span>

      {live && post.image && (
        <span className="substack-card__media">
          <img src={post.image} alt="" loading="lazy" />
        </span>
      )}

      <span className="substack-card__title">
        {live ? post.title : "Field notes on velocity, operating systems & building well."}
      </span>

      {live && post.blurb && (
        <span className="substack-card__blurb">{post.blurb}</span>
      )}

      <span className="substack-card__cta">
        {live ? "Read the latest" : "Read the newsletter"} &rarr;
      </span>
    </a>
  );
}

/* Custom OnVelocity signup — a zine-styled email box. On submit it hands off
   to Substack's subscribe page with the email prefilled (opens in a new tab),
   so there's no backend and the styling stays on-brand. */
function SubstackSignup() {
  const [email, setEmail] = useStateLD("");
  const [done, setDone]   = useStateLD(false);

  function onSubmit(e) {
    e.preventDefault();
    const v = email.trim();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v)) return;
    window.open(SUBSTACK_URL + "/subscribe?email=" + encodeURIComponent(v), "_blank", "noopener,noreferrer");
    setDone(true);
  }

  return (
    <form className="substack-signup" onSubmit={onSubmit}>
      <label className="substack-signup__label" htmlFor="substack-email">
        {SUBSTACK_ICON}
        <span>Get OnVelocity in your inbox</span>
      </label>
      {done ? (
        <p className="substack-signup__done">
          Thanks! Confirm your subscription in the Substack tab that just opened. &nbsp;
          <button type="button" className="substack-signup__again" onClick={() => { setDone(false); setEmail(""); }}>
            Use a different email
          </button>
        </p>
      ) : (
        <div className="substack-signup__row">
          <input
            id="substack-email"
            type="email"
            className="substack-signup__input"
            placeholder="you@email.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoComplete="email"
            aria-label="Email address" />
          <button type="submit" className="substack-signup__btn">Subscribe &rarr;</button>
        </div>
      )}
    </form>
  );
}

const LEADERSHIP_TABS = [
  /* Tab 1 — How I Lead. Includes the AI POV content folded into the body
     and one AI-aware pillar so it's expressed as a leadership stance rather
     than a separate category. */
  {
    id: "lead",
    label: "How I Lead",
    tabSub: "day-to-day",
    eyebrow: "Practice · Twenty years on",
    title: "How I lead.",
    deck: "",
    body: [
      "I don't subscribe to a single style or solution. Every challenge I've tackled has come with its own context, goals, gaps, and motivations. I seek to read that accurately and adjust accordingly, not simply apply a framework.",
      "What stays constant is the bar I hold for myself and the people around me. Not a bar defined by promotion timelines or performance reviews, but by impact, craft, and growth. I want the people who work with me to leave better than they arrived: sharper in their thinking, more confident in their judgment, and proud of what we built together. If they look back and feel that working with me was a turning point, that is the outcome I am after.",
      "In practice, I lead with clear expectations, meaningful autonomy, and honest feedback. I don't micromanage, but I do flex the level of support I provide based on what someone actually needs. I value independent research and rigorous thinking before a room gets together to debate. I want people to come with a point of view, defend it, and be genuinely open to changing it. Pressure-testing is how good ideas get better, and every meaningful initiative should have measurable outcomes we can validate against — because accountability without evidence is just intention.",
      "On AI, my approach is pragmatic. AI doesn't fix broken operating systems; it amplifies them. So I make sure the system underneath is worth amplifying before I deploy it. The PMOs I build use AI to remove friction — automated reporting that frees leaders to lead, decision frameworks that catch what humans miss, capitalization and effort capture that runs in the background instead of eating engineering hours. I'm skeptical of AI as a strategy. I'm bullish on AI as connective tissue — the leverage that lets a 600-person org move with the coherence of a 60-person one. The work stays human. The judgment stays yours.",
    ],
    pillars: [
      {
        word: "Situational by design",
        body: "I read the people and the context before deciding how to show up as a leader. No single style fits every situation.",
      },
      {
        word: "High bar, human approach",
        body: "I hold people to a high standard because I believe in their potential, not to meet a metric or check a box.",
      },
      {
        word: "Autonomy with accountability",
        body: "Clear goals, real ownership, and the support to succeed. I flex involvement based on skill and need, not habit.",
      },
      {
        word: "Debate as a discipline",
        body: "I encourage independent thinking, healthy challenge, and strong opinions loosely held. Pressure-testing is how good ideas get better.",
      },
      {
        word: "Augmentation, not abdication",
        body: "AI sharpens human judgment; it doesn't replace it. The accountability stays with the operator in the room.",
      },
      {
        word: "Leave people better",
        body: "My measure of success as a leader is whether the people I worked with are stronger, more capable, and more confident when they move on.",
      },
    ],
  },

  /* Tab 2 — What I Hold. Merges the prior Values and Throughlines tabs
     into one constant-across-careers section. */
  {
    id: "values",
    label: "What I Hold",
    tabSub: "the constants",
    eyebrow: "Values & throughlines · 2005 → Present",
    title: "What I hold.",
    /* Panel deck removed — the shared "Across very different environments..."
       line now lives above the pillars list on the right (and applies to both
       tabs), so it would duplicate here. */
    deck: "",
    body: [
      "I've built and refined operating systems for 10+ companies across twenty years. Different industries, different scales, different stages. What stays constant is my curiosity, adaptability, drive, and ability to bring change to life.",
      "I value data over opinion, and independent thinking before group debate. Outcomes before activity. Accountability with evidence, not accountability as theater. I value teams that argue well in service of shared goals, and leaders who change their minds when the data demands it. I value craft, in writing, in process, in the operating system itself. I value the long arc of a career as a story, not a stack of titles.",
      "These aren't just values I claim — they're throughlines. Patterns that emerged from doing the work, again and again, across very different environments. I look for them in the operators I bring along, the leaders I partner with, and the systems I build. The work changes; these don't.",
    ],
    pillars: [
      { word: "Rigor",      body: "Every assumption is a hypothesis until tested. Strong opinions, loosely held, validated against outcomes." },
      { word: "Builder",    body: "I enter ambiguity and create structure. Every role has involved building something that didn't exist before I arrived." },
      { word: "Multiplier", body: "I make the people around me measurably more effective. Leaders, teams, and orgs are better on the other side." },
      { word: "Architect",  body: "I don't just fix problems. I design systems that prevent them from recurring." },
      { word: "Mentor",     body: "I invest in the people around me even when it isn't my job. That's been true since my very first role." },
      { word: "Trusted",    body: "I earn proximity to senior leaders and handle it with discretion, strong instincts, and genuine care." },
      { word: "The long arc", body: "Careers are stories — not stacks of titles. So is the work I leave behind. I optimize for the arc, not the next move." },
    ],
  },
];

function Leadership() {
  const [active, setActive] = useStateLD(0);
  const tab = LEADERSHIP_TABS[active];

  return (
    <section className="leadership" id="leadership" data-screen-label="Leadership · AI · Values">
      <div className="page leadership__page">
        <header className="leadership__header">
          <div className="leadership__header-text">
            <p className="dateline leadership__eyebrow">{tab.eyebrow}</p>
            <h2 className="leadership__title">
              More about <em>me.</em>
            </h2>
            <p className="leadership__deck">
              <strong>Anastasia Vastola</strong> &mdash; Dreamer, builder, guide
            </p>
            <dl className="leadership__location">
              <dt>Based</dt>
              <dd>Detroit, MI &middot; Remote</dd>
              <a
                className="leadership__substack"
                href="https://onvelocity.substack.com"
                target="_blank"
                rel="noopener noreferrer">
                <svg className="leadership__substack-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                  <path d="M22.539 8.242H1.46V5.406h21.08v2.836zM1.46 10.812V24L12 18.11 22.54 24V10.812H1.46zM22.539 0H1.46v2.836h21.08V0z" />
                </svg>
                <span>OnVelocity</span>
              </a>
            </dl>
          </div>
          {/* Polaroid — smaller, top-right of the section. Brought back from
              the old Editor's note section. */}
          <div className="leadership__polaroid">
            {typeof RotatingPolaroid !== "undefined" && <RotatingPolaroid />}
          </div>
        </header>

        {/* Tabs */}
        <div className="leadership__tabs" role="tablist" aria-label="More about me">
          {LEADERSHIP_TABS.map((t, i) => (
            <button
              key={t.id}
              role="tab"
              aria-selected={i === active}
              data-active={i === active}
              className="leadership-tab"
              onClick={() => setActive(i)}>
              <span className="leadership-tab__index">0{i + 1}</span>
              <span className="leadership-tab__label">{t.label}</span>
              {t.tabSub && <span className="leadership-tab__sub">{t.tabSub}</span>}
              <span className="leadership-tab__indicator" aria-hidden="true" />
            </button>
          ))}
        </div>

        {/* Active panel */}
        <div className="leadership__panel" role="tabpanel" key={tab.id}>
          <div className="leadership__panel-head">
            <h3 className="leadership__panel-title">{tab.title}</h3>
            {tab.deck && <p className="leadership__panel-deck">{tab.deck}</p>}
          </div>

          <div className="leadership__panel-body">
            <div className="leadership__prose">
              {tab.body.map((p, i) => (
                <p key={i} className={i === 0 ? "leadership__prose-lead" : ""}>{p}</p>
              ))}
            </div>

            <div className="leadership__pillars-wrap">
              <p className="leadership__pillars-header">
                Across very different environments, from agency to enterprise
                to startup, three people to several hundred&mdash;these stay
                constant.
              </p>
              <ol className="leadership__pillars">
                {tab.pillars.map((p, i) => (
                  <li key={p.word} className="leadership-pillar">
                    <span className="leadership-pillar__num">{String(i + 1).padStart(2, "0")}</span>
                    <div className="leadership-pillar__body">
                      <p className="leadership-pillar__word">{p.word}</p>
                      <p className="leadership-pillar__copy">{p.body}</p>
                    </div>
                  </li>
                ))}
              </ol>

              <SubstackLatest />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Leadership, SubstackSignup });
