// SolutionSection - the most creative section on the page.
// A by-WORKFLOW tabbed slider (six tabs, organized by task so every ICP
// sees itself). Selecting a tab moves a gold underline beneath the active
// tab and crossfades a single wide editorial panel below it. The rail is a
// deliberate two-row grid so six labels read as a composed set, not a
// wrapped accident; the underline is positioned per-button so it tracks
// correctly across both rows. Before -> after stat pair treated like the
// brand stat-card. Dependency-free: React state (useState/useEffect/useRef)
// + a scoped <style> block. Honors prefers-reduced-motion by freezing to a
// static, fully-readable state.
//
// Reuses window globals: SectionLabel, Headline, Callout.

const SolutionSection = () => {
  const { useState, useRef, useEffect, useLayoutEffect } = React;

  const TABS = [
    {
      id: 'underwriting',
      label: 'Underwriting',
      sub: 'For the capital-side desk.',
      promise:
        'More deals per quarter without doubling the team. Audit-grade IC memos in hours, not days.',
      from: '40 hrs',
      to: '4 hrs',
      note: 'per deal',
    },
    {
      id: 'origination',
      label: 'Origination',
      sub: 'For lenders and brokers.',
      promise:
        'Broker email to a reviewable initial screen in hours, not weeks. Bid on twice the pipeline with the desk you already have.',
      from: 'weeks',
      to: 'hours',
      note: 'email to screen',
    },
    {
      id: 'applications',
      label: 'Applications',
      sub: 'For mission-led developers, HFAs, and PHAs.',
      promise:
        'LIHTC and NOFA applications assembled in days, not months. Hit every award window without burning out the team.',
      from: 'months',
      to: 'days',
      note: 'per application',
    },
    {
      id: 'compliance',
      label: 'Compliance & Legal',
      sub: 'For operators, asset managers, and legal teams.',
      promise:
        'A compliance and legal posture that never costs you a finding. LURA, HOTMA, PHAS, SEMAP, 8609, REAC, plus the legal and regulatory review that stalls deals, handled in the background.',
      from: '6+ frameworks',
      to: 'automated',
      note: 'tracked by hand',
    },
    {
      id: 'assets',
      label: 'Asset Management',
      sub: 'For owners and property managers.',
      promise:
        'The first eight hours of every deal back. Reporting and stewardship done so the team can do the partnership work in the foreground.',
      from: '8 hrs',
      to: 'to the team',
      note: 'every deal',
    },
    {
      id: 'operations',
      label: 'Operations',
      sub: 'For CEOs and the C-suite.',
      promise:
        'An AI operating layer for the whole firm. Live dashboards across underwriting, origination, and compliance, so leadership sees what is working, what is stuck, and where the next hour should go. The answer your board has been asking for.',
      from: 'every workflow',
      to: 'one view',
      note: 'across the firm',
    },
  ];

  const [active, setActive] = useState(0);
  const railRef = useRef(null);
  const btnRefs = useRef([]);
  const [underline, setUnderline] = useState({ left: 0, top: 0, width: 0, ready: false });

  // Position the gold underline directly beneath the active tab. Because the
  // rail is a two-row grid, we track BOTH left and top so the underline sits
  // on the correct row. Recompute on resize and after fonts settle.
  const positionUnderline = () => {
    const rail = railRef.current;
    const btn = btnRefs.current[active];
    if (!rail || !btn) return;
    const rb = rail.getBoundingClientRect();
    const bb = btn.getBoundingClientRect();
    setUnderline({
      left: bb.left - rb.left,
      top: bb.bottom - rb.top,
      width: bb.width,
      ready: true,
    });
  };

  useLayoutEffect(() => {
    positionUnderline();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [active]);

  useEffect(() => {
    const onResize = () => positionUnderline();
    window.addEventListener('resize', onResize);
    // Reposition once fonts have settled (Cormorant/DM Mono load async).
    const t = setTimeout(positionUnderline, 220);
    if (document.fonts && document.fonts.ready) {
      document.fonts.ready.then(positionUnderline).catch(() => {});
    }
    return () => {
      window.removeEventListener('resize', onResize);
      clearTimeout(t);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Keyboard navigation along the rail (left/right/home/end).
  const onKeyDown = (e) => {
    let next = null;
    if (e.key === 'ArrowRight') next = (active + 1) % TABS.length;
    else if (e.key === 'ArrowLeft') next = (active - 1 + TABS.length) % TABS.length;
    else if (e.key === 'Home') next = 0;
    else if (e.key === 'End') next = TABS.length - 1;
    if (next !== null) {
      e.preventDefault();
      setActive(next);
      const b = btnRefs.current[next];
      if (b) b.focus();
    }
  };

  return (
    <section id="solution" className="section soln">
      {/* Layered gold/coral gradient wash, behind everything. */}
      <div className="soln__wash" aria-hidden />
      <div className="container soln__inner">
        <SectionLabel number="03">The Solution</SectionLabel>

        {/* Relief pull-line - italic Cormorant, the quiet opener. */}
        <p className="soln__relief">
          Our clients are not buying another AI workflow. They are buying
          relief. The clarity, purpose, and confidence to move through a noisy
          AI landscape and know the next decision is the right one.
        </p>

        {/* Headline (Option D, locked). Only "judgment" gold italic. */}
        <Headline as="h2" size="d2" style={{ marginTop: 22, maxWidth: 920 }}>
          We turn the forty-hour underwrite into four hours of{' '}
          <em style={{ color: 'var(--fg-accent)', fontWeight: 500 }}>judgment.</em>
        </Headline>

        {/* One-line lead - supporting. */}
        <p className="lead soln__lead">
          We rebuild the workflows that run a mission-driven housing firm around
          what AI does today, inside the tools you already use. Pick the work
          that is costing you the most time.
        </p>

        {/* The centerpiece: by-workflow tabbed slider. */}
        <div className="soln__slider">
          {/* DM Mono tab rail (deliberate two-row grid) + sliding underline. */}
          <div
            className="soln__rail"
            role="tablist"
            aria-label="Workflows we rebuild"
            ref={railRef}
            onKeyDown={onKeyDown}
          >
            {TABS.map((t, i) => (
              <button
                key={t.id}
                ref={(el) => (btnRefs.current[i] = el)}
                role="tab"
                id={`soln-tab-${t.id}`}
                aria-selected={i === active}
                aria-controls={`soln-panel-${t.id}`}
                tabIndex={i === active ? 0 : -1}
                className={'soln__tab' + (i === active ? ' is-active' : '')}
                onClick={() => setActive(i)}
                type="button"
              >
                {t.label}
              </button>
            ))}
            <span
              className="soln__underline"
              aria-hidden
              style={{
                transform: `translate(${underline.left}px, ${underline.top}px)`,
                width: underline.width,
                opacity: underline.ready ? 1 : 0,
              }}
            />
          </div>

          {/* One wide editorial panel that crossfades on tab change. */}
          <div className="soln__stage">
            {TABS.map((t, i) => (
              <div
                key={t.id}
                role="tabpanel"
                id={`soln-panel-${t.id}`}
                aria-labelledby={`soln-tab-${t.id}`}
                aria-hidden={i !== active}
                className={'soln__panel' + (i === active ? ' is-active' : '')}
              >
                <div className="soln__panelGrid">
                  <div className="soln__panelCopy">
                    <div className="soln__buyer">{t.sub}</div>
                    <p className="soln__promise">{t.promise}</p>
                  </div>

                  {/* before -> after stat pair, brand stat-card treatment. */}
                  <div className="soln__statcard">
                    <div className="soln__statNote">{t.note}</div>
                    <div className="soln__statRow">
                      <span className="soln__statFrom">{t.from}</span>
                      <span className="soln__statArrow" aria-hidden>
                        &rarr;
                      </span>
                      <span className="soln__statTo">{t.to}</span>
                    </div>
                    <div className="soln__statCaption">
                      <span className="soln__statCapWord">before</span>
                      <span className="soln__statCapWord soln__statCapWord--to">
                        after
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Confidence beat - gold-bordered callout (own-portfolio line CUT). */}
        <Callout eyebrow="Why us" style={{ marginTop: 0 }}>
          We are not an AI shop learning your business on your budget. We have
          closed five and a half billion dollars in these deals and housed twenty-two
          thousand families.
        </Callout>

        {/* One-line transition to the Engagement section. */}
        <p className="soln__transition">
          Knowing which workflow to rebuild first is where every engagement
          starts.
        </p>
      </div>

      <style>{`
        .soln { position: relative; overflow: hidden; }

        /* Layered gold/coral gradient wash for depth. Coral stays rationed
           to the single existing accent already present in the wash. */
        .soln__wash {
          position: absolute; inset: 0; z-index: 0; pointer-events: none;
          background:
            radial-gradient(62% 48% at 82% 8%, rgba(201,168,76,0.13), transparent 66%),
            radial-gradient(48% 42% at 6% 96%, rgba(228,88,106,0.07), transparent 70%);
        }

        /* Even vertical rhythm: every beat sets its own top margin so the
           section reads top-to-bottom with one deliberate cadence. */
        .soln__inner { position: relative; z-index: 1; }

        /* Opener: quiet. */
        .soln__relief {
          font-family: var(--font-display);
          font-style: italic; font-weight: 500;
          font-size: clamp(22px, 2.4vw, 30px);
          line-height: 1.34; letter-spacing: -0.01em;
          color: var(--fg-accent-soft);
          max-width: 760px; margin: 28px 0 0;
          text-wrap: pretty;
        }

        /* Lead: supporting. */
        .soln__lead { margin: 22px 0 0; max-width: 780px; }

        /* ---------- The slider: the centerpiece ---------- */
        .soln__slider { margin-top: 64px; }

        /* Two-row tab grid: three columns, even spacing. Reads as a composed
           set rather than an accidental wrap. The underline tracks rows. */
        .soln__rail {
          position: relative;
          display: grid;
          grid-template-columns: repeat(3, minmax(0, 1fr));
          column-gap: clamp(20px, 3vw, 44px);
          row-gap: 0;
          border-bottom: 1px solid var(--border-soft);
        }
        .soln__tab {
          appearance: none; background: transparent; border: 0;
          cursor: pointer; margin: 0;
          padding: 16px 0;
          text-align: left;
          font-family: var(--font-mono);
          font-size: 12px; font-weight: 400;
          letter-spacing: 0.18em; text-transform: uppercase;
          color: var(--fg-2);
          transition: color var(--dur-base) var(--ease-editorial);
          position: relative;
        }
        /* Hairline separators between rows of the grid (rows 4-6). */
        .soln__tab:nth-child(n + 4) {
          border-top: 1px solid var(--border-soft);
        }
        .soln__tab:hover { color: var(--fg-1); }
        .soln__tab.is-active { color: var(--fg-accent); }
        .soln__tab:focus-visible {
          outline: 2px solid var(--border-gold);
          outline-offset: 3px; border-radius: 2px;
        }
        /* The sliding gold underline - the single active-tab motif. It is
           anchored top-left and moved with translate() to the active tab's
           bottom edge, so it lands on the correct row of the grid. */
        .soln__underline {
          position: absolute; top: 0; left: 0; height: 2px;
          margin-top: -1px;
          background: var(--gold);
          box-shadow: 0 0 12px -2px rgba(201,168,76,0.6);
          transition:
            transform var(--dur-slow) var(--ease-editorial),
            width var(--dur-slow) var(--ease-editorial),
            opacity var(--dur-base) var(--ease-editorial);
          will-change: transform, width;
        }

        /* ---------- The stage: crossfading panels ---------- */
        .soln__stage {
          position: relative;
          display: grid;
          margin-top: 0;
          /* hairline-framed editorial panel */
          border: 1px solid var(--border-soft);
          border-top: 0;
          border-radius: 0 0 8px 8px;
          background: var(--bg-elev-1);
          box-shadow: var(--shadow-soft);
          overflow: hidden;
        }
        /* gold hairline accent down the left edge of the stage */
        .soln__stage::before {
          content: ""; position: absolute; left: 0; top: 0; bottom: 0;
          width: 2px; background: var(--rule-gold); opacity: 0.5;
        }

        /* Panels stack in one grid cell; the tallest sets the stage height. */
        .soln__panel {
          grid-area: 1 / 1;
          opacity: 0; visibility: hidden;
          transition:
            opacity var(--dur-slow) var(--ease-editorial),
            visibility 0s linear var(--dur-slow);
          padding: clamp(36px, 4vw, 56px) clamp(30px, 4vw, 64px);
        }
        .soln__panel.is-active {
          opacity: 1; visibility: visible;
          transition:
            opacity var(--dur-slow) var(--ease-editorial),
            visibility 0s;
        }

        /* Calm two-column composition. Copy left, stat card right, both
           top-aligned so the buyer label and the stat note share a baseline. */
        .soln__panelGrid {
          display: grid;
          grid-template-columns: minmax(0, 1.5fr) minmax(260px, 0.85fr);
          gap: clamp(36px, 5vw, 72px);
          align-items: start;
        }

        .soln__panelCopy { min-width: 0; }
        .soln__buyer {
          font-family: var(--font-mono);
          font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase;
          color: var(--fg-accent); margin-bottom: 20px;
        }
        .soln__promise {
          font-family: var(--font-display);
          font-size: clamp(26px, 2.8vw, 36px);
          line-height: 1.24; letter-spacing: -0.01em; font-weight: 500;
          color: var(--fg-1); margin: 0; text-wrap: pretty;
        }

        /* before -> after stat card - the unambiguous visual home for the
           metric: gold-bordered, inset surface, clearly framed. */
        .soln__statcard {
          border: 1px solid var(--border-gold);
          border-radius: 8px;
          background: var(--bg-elev-2);
          padding: 28px 30px;
          position: relative;
          align-self: start;
        }
        .soln__statNote {
          font-family: var(--font-mono);
          font-size: 10px; letter-spacing: 0.22em; text-transform: uppercase;
          color: var(--fg-2); margin-bottom: 20px;
        }
        .soln__statRow {
          display: flex; align-items: baseline; flex-wrap: wrap; gap: 12px;
        }
        .soln__statFrom {
          font-family: var(--font-display);
          font-size: clamp(30px, 3.2vw, 44px);
          line-height: 1; letter-spacing: -0.02em; font-weight: 500;
          color: var(--fg-2);
        }
        .soln__statArrow {
          font-family: var(--font-display);
          font-size: clamp(26px, 2.8vw, 38px);
          line-height: 1; color: var(--coral); font-weight: 500;
        }
        .soln__statTo {
          font-family: var(--font-display);
          font-size: clamp(34px, 3.8vw, 52px);
          line-height: 1; letter-spacing: -0.02em; font-weight: 500;
          color: var(--fg-accent);
        }
        .soln__statCaption {
          display: flex; justify-content: space-between;
          margin-top: 20px; padding-top: 14px;
          border-top: 1px solid var(--border-soft);
        }
        .soln__statCapWord {
          font-family: var(--font-mono);
          font-size: 10px; letter-spacing: 0.22em; text-transform: uppercase;
          color: var(--fg-2);
        }
        .soln__statCapWord--to { color: var(--fg-accent); }

        /* Confidence beat: a distinct closing block, evenly set off. */
        .soln__inner > aside { margin-top: 72px; }

        /* Transition line to Engagement - quiet, italic close. */
        .soln__transition {
          font-family: var(--font-display);
          font-style: italic; font-weight: 500;
          font-size: clamp(20px, 2vw, 26px);
          line-height: 1.3; color: var(--fg-2);
          max-width: 640px; margin: 36px 0 0; text-wrap: pretty;
        }

        /* ---------- Tablet: rail to two columns ---------- */
        @media (max-width: 920px) {
          .soln__rail {
            grid-template-columns: repeat(2, minmax(0, 1fr));
            column-gap: 28px;
          }
          /* Reset desktop row separators, apply for 2-col layout (rows 3-6). */
          .soln__tab:nth-child(n + 4) { border-top: 0; }
          .soln__tab:nth-child(n + 3) { border-top: 1px solid var(--border-soft); }
        }

        /* ---------- Mobile: single column throughout ---------- */
        @media (max-width: 600px) {
          .soln__panelGrid { grid-template-columns: 1fr; gap: 28px; align-items: start; }
          .soln__rail { grid-template-columns: 1fr; column-gap: 0; }
          .soln__tab { padding: 14px 0; }
          .soln__tab:nth-child(n + 3) { border-top: 0; }
          .soln__tab:nth-child(n + 2) { border-top: 1px solid var(--border-soft); }
        }

        /* ---------- prefers-reduced-motion: freeze to a static, readable state ---------- */
        @media (prefers-reduced-motion: reduce) {
          .soln__underline { transition: none; }
          .soln__tab { transition: none; }
          .soln__panel { transition: none; }
          html, body { scroll-behavior: auto; }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { SolutionSection });
