/* lets-partner.jsx — page components for the "Working Life" volume.
 *
 * Defines three page-level pieces:
 *   • RolesSection  — the 4 roles as tabs on a horizontal rule + the active
 *                     role's copy below. Deep-linkable via #/<slug> (driven by
 *                     activeSlug + onSelectRole, owned by app.jsx). Tan palette,
 *                     no black box. Lives on the ABOUT ME page now.
 *   • AboutMe       — the default landing: a page header → RolesSection →
 *                     <Leadership /> (How I lead · What I hold).
 *   • ServicesPage  — the standalone "Services" page: header + sub-header +
 *                     the "How we engage / four ways in" material + CTA.
 */
/* global React, ReactDOM, ROLES, ENGAGEMENT_MODES, Leadership, Bloom, Splatter */

const { useEffect: useEffectLP, useRef: useRefLP } = React;

/* ============================================================
   MobileNavTray — shared left slide-out drawer for the mobile
   sub-navigation. Reused by the About-me roles strip (below) and
   the career-story timeline (career-journey.jsx, which loads after
   this file, so window.MobileNavTray is defined by then).

   The TRIGGER renders in normal flow and is shown only at narrow
   widths via CSS — a single "where am I" bar carrying the current
   selection. The SCRIM + PANEL are portaled to <body> so the fixed
   drawer is never clipped by a sticky or overflow-scrolling ancestor
   (the masthead, the sticky timeline, the scroll strips).

   Props:
     eyebrow  — mono kicker shown on the trigger + panel head
     current  — { num, label } painted on the closed trigger so the
                reader always sees where they are without opening
     title    — the panel heading (also the dialog's a11y label)
     children — render-prop: (close) => tray body. `close` lets an
                item dismiss the tray the moment it's selected.
   ============================================================ */
function MobileNavTray({ eyebrow, current, title, children }) {
  const [open, setOpen] = React.useState(false);
  const panelRef = React.useRef(null);
  const close = React.useCallback(() => setOpen(false), []);

  /* While open: lock body scroll, wire ESC, and move focus into the
     panel for keyboard + screen-reader users. All undone on close. */
  React.useEffect(() => {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    function onKey(e) { if (e.key === "Escape") setOpen(false); }
    document.addEventListener("keydown", onKey);
    const t = setTimeout(() => { if (panelRef.current) panelRef.current.focus(); }, 40);
    return () => {
      document.body.style.overflow = prevOverflow;
      document.removeEventListener("keydown", onKey);
      clearTimeout(t);
    };
  }, [open]);

  const drawer = (
    <div className={`mnav${open ? " is-open" : ""}`} aria-hidden={open ? undefined : "true"}>
      <div className="mnav__scrim" onClick={close} />
      <div
        className="mnav__panel"
        role="dialog"
        aria-modal="true"
        aria-label={title}
        tabIndex={-1}
        ref={panelRef}>
        <div className="mnav__head">
          <span className="mnav__eyebrow">{eyebrow}</span>
          <h2 className="mnav__title">{title}</h2>
          <button type="button" className="mnav__close" onClick={close} aria-label="Close menu">
            <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
              <path d="M6 6l12 12M18 6L6 18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />
            </svg>
          </button>
        </div>
        <div className="mnav__body">
          {typeof children === "function" ? children(close) : children}
        </div>
      </div>
    </div>
  );

  return (
    <>
      <button
        type="button"
        className="mnav-trigger"
        aria-haspopup="dialog"
        aria-expanded={open}
        onClick={() => setOpen(true)}>
        <span className="mnav-trigger__text">
          <span className="mnav-trigger__kicker">{eyebrow}</span>
          <span className="mnav-trigger__current">
            {current && current.num ? <span className="mnav-trigger__num">{current.num}</span> : null}
            <span className="mnav-trigger__label">{current ? current.label : title}</span>
          </span>
        </span>
        <span className="mnav-trigger__cue" aria-hidden="true">
          <svg viewBox="0 0 24 24" focusable="false">
            <path d="M4 7h16M4 12h16M4 17h16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
          </svg>
        </span>
      </button>
      {ReactDOM.createPortal(drawer, document.body)}
    </>
  );
}

/* ============================================================
   RolesSection — 4 role tabs + the active role's panel.
   ============================================================ */
function RolesSection({ activeSlug, onSelectRole }) {
  const roles = (typeof ROLES !== "undefined" && ROLES) || [];
  /* No hash → default the first role active. A valid slug → that role active. */
  const openSlug = activeSlug || (roles[0] && roles[0].slug) || null;
  const activeRole = roles.find((r) => r.slug === openSlug) || roles[0] || null;
  const didDeepLink = useRefLP(Boolean(activeSlug));

  /* If the visitor arrived via a role-specific URL, the matching tab is already
     active — bring the tab strip into view once on mount so the deep link
     lands on the relevant content. */
  useEffectLP(() => {
    if (!didDeepLink.current || !openSlug) return;
    const t = setTimeout(() => {
      const el = document.getElementById("roles-tabs");
      if (el) {
        const y = el.getBoundingClientRect().top + window.scrollY - 130;
        window.scrollTo({ top: y, behavior: "smooth" });
      }
    }, 120);
    return () => clearTimeout(t);
  }, []);

  if (!activeRole) return null;
  const sell = activeRole.sell || {};

  return (
    <div className="roles-section">
      {/* Tabs sit on the horizontal rule; selecting one swaps the copy below
          and updates the #/<slug> hash (no reload). */}
      <div className="lp-tabs-wrap" id="roles-tabs">
        <div className="lp-tabs" role="tablist" aria-label="The four roles I play">
          {roles.map((r) => {
            const active = openSlug === r.slug;
            return (
              <button
                key={r.id}
                type="button"
                role="tab"
                id={`tab-${r.slug}`}
                aria-selected={active}
                aria-controls={`panel-${r.slug}`}
                data-active={active}
                className="lp-tab"
                onClick={() => onSelectRole(r.slug)}>
                <span className="lp-tab__num">{r.num}</span>
                <span className="lp-tab__title">{r.title}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Mobile: the four-up tab strip collapses to a left slide-out tray.
          The trigger shows the active role; the tray lists all four. */}
      <MobileNavTray
        eyebrow="The roles"
        current={{ num: activeRole.num, label: activeRole.title }}
        title="Four roles I play">
        {(close) => (
          <ul className="mnav-list" role="list">
            {roles.map((r) => {
              const active = openSlug === r.slug;
              return (
                <li key={r.id}>
                  <button
                    type="button"
                    className="mnav-item"
                    data-active={active}
                    aria-current={active ? "true" : undefined}
                    onClick={() => { onSelectRole(r.slug); close(); }}>
                    <span className="mnav-item__num">{r.num}</span>
                    <span className="mnav-item__title">{r.title}</span>
                    {active && <span className="mnav-item__here">you&rsquo;re here</span>}
                  </button>
                </li>
              );
            })}
          </ul>
        )}
      </MobileNavTray>

      {/* Active role panel — clearer hierarchy: a lead statement, then the
          specific problems, then the outcome + what it looks like + CTA.
          Tan treatment throughout (no black box). */}
      <div
        className="lp-panel"
        id={`panel-${activeRole.slug}`}
        role="tabpanel"
        aria-labelledby={`tab-${activeRole.slug}`}
        key={activeRole.slug}>

        <div className="lp-role__cols">
          {/* LEFT — the role header (No. + title, top-aligned with the right
              column's "problems" header), then the main copy, "what it looks
              like in practice", and the CTA. */}
          <div className="lp-role__left">
            {/* Role header — names the active role; changes when you switch tabs. */}
            <header className="lp-role__head">
              <span className="lp-role__head-num">{activeRole.num}</span>
              <h3 className="lp-role__head-title">{activeRole.title}</h3>
            </header>

            {/* Lead — the outcome statement combined with the role summary. */}
            <p className="lp-role__lead">
              {sell.outcome ? `${sell.outcome} ` : ""}{sell.value}
            </p>

            <div className="lp-role__practice">
              <div className="role-panel__divider"><span>What it looks like in practice</span></div>
              <ul className="lp-role__practice-list">
                {(activeRole.looksLike || []).map((b, i) => (
                  <li key={i}><span className="lp-role__bullet" aria-hidden="true">✦</span> {b}</li>
                ))}
              </ul>
            </div>

            <a
              href="https://www.linkedin.com/in/avastola/"
              target="_blank"
              rel="noopener noreferrer"
              className="lp-role__cta">
              Let&rsquo;s connect &rarr;
            </a>
          </div>

          {/* RIGHT — the specific problems this role solves. */}
          <div className="lp-role__right">
            <div className="lp-role__problems">
              <p className="lp-role__kicker hand">The problems I solve</p>
              <ol className="lp-role__problem-list">
                {(sell.problems || []).map((p, i) => (
                  <li key={i} className="lp-problem">
                    <span className="lp-problem__num">{String(i + 1).padStart(2, "0")}</span>
                    <div className="lp-problem__text">
                      <p className="lp-problem__title">{p.title}</p>
                      <p className="lp-problem__body">{p.body}</p>
                    </div>
                  </li>
                ))}
              </ol>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   AboutMe — default landing. New page header → roles → Leadership.
   ============================================================ */
function AboutMe({ activeSlug, onSelectRole }) {
  return (
    <section className="about-me" id="about" data-screen-label="00 About me">
      {/* Watercolour atmosphere — blooms + ink/accent specks, matching the
          Career story page's speck style. */}
      {typeof Bloom !== "undefined" && (
        <>
          <Bloom color="var(--accent)" size={460} top={-130} left={-150} seed={5} opacity={0.5} />
          <Bloom color="var(--bloom)" size={380} top={"40%"} left={"84%"} seed={9} opacity={0.4} />
        </>
      )}
      {typeof Splatter !== "undefined" && (
        <>
          <Splatter color="var(--ink)" size={220} seed={11} style={{ top: "9%", right: "5%" }} />
          <Splatter color="var(--accent)" size={180} seed={19} style={{ top: "62%", left: "4%" }} />
          <Splatter color="var(--ink)" size={170} seed={23} style={{ top: "88%", right: "9%" }} />
        </>
      )}

      <div className="page about-me__page">
        {/* Eyebrow + header (sub-header removed for a simpler page). */}
        <header className="about-me__hero">
          <div className="eyebrow"><span>About me &middot; Anastasia Vastola</span></div>
          <h1 className="about-me__headline">Four Areas of <span className="svc__hl">Expertise</span></h1>
        </header>

        {/* The four roles (moved here from the Services page) */}
        <RolesSection activeSlug={activeSlug} onSelectRole={onSelectRole} />

        {/* Cross-promo → Services (#services) + Career story (#journey). */}
        <div className="xpromo">
          {typeof SubstackSignup !== "undefined" && <SubstackSignup />}
          <a className="xpromo__link" href="#services">How we engage &rarr;</a>
          <a className="xpromo__link" href="#journey">View case studies &rarr;</a>
        </div>
      </div>

      {/* Existing About me content — How I lead · What I hold (unchanged copy). */}
      {typeof Leadership !== "undefined" && <Leadership />}
    </section>
  );
}

/* ============================================================
   ServicesPage — standalone "Services" page: header + sub-header
   + "How we engage / four ways in" + closing CTA.
   ============================================================ */
function ServicesPage() {
  return (
    <section className="lp svc" id="services" data-screen-label="00 Services">
      {typeof Bloom !== "undefined" && (
        <>
          <Bloom color="var(--accent)" size={460} top={-130} left={-150} seed={5} opacity={0.5} />
          <Bloom color="var(--bloom)" size={380} top={"42%"} left={"82%"} seed={9} opacity={0.4} />
        </>
      )}

      <div className="page lp__page">
        {/* Page eyebrow only — headline + sub-header removed for a simpler page. */}
        <header className="svc__hero">
          <div className="eyebrow"><span>Services &middot; For founders, executives &amp; operators</span></div>
        </header>

        {/* ===== HOW WE ENGAGE — the full "four ways in" material ===== */}
        <div className="engage-block">
          <div className="engage-block__head">
            <span className="tape" style={{ background: "var(--accent)", color: "var(--paper)" }}>How we engage</span>
            <h3 className="engage-block__title">Four ways in</h3>
          </div>

          <div className="engage-grid">
            {(typeof ENGAGEMENT_MODES !== "undefined" ? ENGAGEMENT_MODES : []).map((m) => (
              <div key={m.n} className="engage-card">
                <div className="engage-card__num">{m.n}</div>
                <h4 className="engage-card__title">{m.title}</h4>
                <p className="engage-card__duration">{m.duration}</p>
                <p className="engage-card__body">{m.body}</p>
              </div>
            ))}
          </div>

          <div className="engage-block__cta">
            <a
              href="https://www.linkedin.com/in/avastola/"
              className="linkbtn"
              target="_blank"
              rel="noopener noreferrer">
              Start a conversation &rarr;
            </a>
          </div>
        </div>

        {/* Cross-promo → the Career story page (#journey switches the view). */}
        <div className="xpromo">
          {typeof SubstackSignup !== "undefined" && <SubstackSignup />}
          <span className="xpromo__label">Want the proof?</span>
          <a className="xpromo__link" href="#journey">View case studies &rarr;</a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { RolesSection, AboutMe, ServicesPage, MobileNavTray });
