// Homepage: Hero, Proposition, Services overview, Segment grid (illustrated), Selected work, Logos, Closer

function CompassWidget({ setRoute }) {
  const SVCS = [
    { bearing: '000°', tag: 'STRATEGY',  label: 'Strategy', sub: 'Stakeholder alignment before big investments.', route: 'strategy' },
    { bearing: '120°', tag: 'AI ADOPT',  label: 'AI Adoption',       sub: 'Applications piloted carefully, built to last.', route: 'ai-adoption' },
    { bearing: '240°', tag: 'DIGITAL',   label: 'Technology',        sub: 'Websites, software, and workflow systems.', route: 'technology' },
  ];

  const [active, setActive] = React.useState(0);
  const rotRef = React.useRef(0);
  const [rotation, setRotation] = React.useState(0);

  const goTo = (idx) => {
    if (idx === active) return;
    const steps = ((idx - active) % 3 + 3) % 3;
    rotRef.current -= steps * 120;
    setRotation(rotRef.current);
    setActive(idx);
  };

  React.useEffect(() => {
    const t = setInterval(() => {
      setActive(prev => {
        const next = (prev + 1) % 3;
        rotRef.current -= 120;
        setRotation(rotRef.current);
        return next;
      });
    }, 7000);
    return () => clearInterval(t);
  }, []);

  const cx = 180, cy = 240, R = 145, hub = 58;
  const brass = '#C9A55A';
  const cream = '#FAF7F1';

  const pt = (bearing, r) => {
    const rad = (bearing - 90) * Math.PI / 180;
    return [cx + r * Math.cos(rad), cy + r * Math.sin(rad)];
  };

  const nord = SVCS[active];
  const se   = SVCS[(active + 1) % 3];
  const sw   = SVCS[(active + 2) % 3];

  return (
    <div style={{ width: '100%' }}>
      <svg viewBox="0 0 360 430" style={{ width: '100%', overflow: 'visible', display: 'block' }} aria-label="Service compass">
        <defs>
          <marker id="arr-on"  markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto" markerUnits="userSpaceOnUse">
            <polygon points="0,0 0,8 7,4" fill={brass} opacity="0.9" />
          </marker>
          <marker id="arr-off" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto" markerUnits="userSpaceOnUse">
            <polygon points="0,0 0,8 7,4" fill={cream} opacity="0.18" />
          </marker>
        </defs>

        {/* Outer rings — fixed */}
        <circle cx={cx} cy={cy} r={R} fill="none" stroke="rgba(250,247,241,0.12)" strokeWidth="1.2" />
        <circle cx={cx} cy={cy} r={R * 0.62} fill="none" stroke="rgba(250,247,241,0.06)" strokeWidth="0.8" />

        {/* Tick marks every 10°, major at 90° */}
        {Array.from({ length: 36 }, (_, i) => {
          const a = i * 10;
          const major = i % 9 === 0, mid = i % 3 === 0;
          const len = major ? 14 : mid ? 9 : 5;
          const [x1, y1] = pt(a, R - 2);
          const [x2, y2] = pt(a, R - len);
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
            stroke={major ? 'rgba(250,247,241,0.28)' : 'rgba(250,247,241,0.13)'}
            strokeWidth={major ? 1.2 : 0.65} />;
        })}

        {/* Cardinal letters */}
        {[['N',0],['E',90],['S',180],['W',270]].map(([l, a]) => {
          const [x, y] = pt(a, R + 19);
          return <text key={l} x={x} y={y} textAnchor="middle" dominantBaseline="middle"
            fill={brass} fontSize="10" fontFamily="'Work Sans',sans-serif"
            fontWeight="700" letterSpacing="2" opacity="0.7">{l}</text>;
        })}

        {/* North label — active service, fades in on change */}
        <g key={`n-${active}`} className="q-compass-lbl-active" onClick={() => setRoute(nord.route)} style={{ cursor: 'pointer' }}>
          <text x={cx} y={36} textAnchor="middle" fill={cream} fontSize="22"
            fontFamily="Georgia,serif" fontStyle="italic" fontWeight="400">
            {nord.label}
          </text>
          <text x={cx} y={58} textAnchor="middle" fill="rgba(250,247,241,0.52)" fontSize="12.5"
            fontFamily="'Work Sans',sans-serif">
            {nord.sub}
          </text>
        </g>

        {/* SE label — next service, dimmed, clickable */}
        <g style={{ cursor: 'pointer' }} onClick={() => goTo((active + 1) % 3)}>
          <text x={352} y={378} textAnchor="end" fill="rgba(250,247,241,0.32)" fontSize="13"
            fontFamily="'Work Sans',sans-serif" fontWeight="500">
            {se.label}
          </text>
        </g>

        {/* SW label — other service, dimmed, clickable */}
        <g style={{ cursor: 'pointer' }} onClick={() => goTo((active + 2) % 3)}>
          <text x={8} y={378} textAnchor="start" fill="rgba(250,247,241,0.32)" fontSize="13"
            fontFamily="'Work Sans',sans-serif" fontWeight="500">
            {sw.label}
          </text>
        </g>

        {/* Rotating: arms + hub */}
        <g style={{
          transformOrigin: `${cx}px ${cy}px`,
          transform: `rotate(${rotation}deg)`,
          transition: 'transform 2s cubic-bezier(0.4, 0, 0.2, 1)',
        }}>
          {[0, 120, 240].map((bearing, i) => {
            const on = i === active;
            const [x1, y1] = pt(bearing, hub + 5);
            const [x2, y2] = pt(bearing, R - 22);
            return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
              stroke={on ? brass : 'rgba(250,247,241,0.16)'}
              strokeWidth={on ? 1.4 : 0.9}
              markerEnd={on ? 'url(#arr-on)' : 'url(#arr-off)'} />;
          })}
          <circle cx={cx} cy={cy} r={hub} fill="rgba(250,247,241,0.04)" stroke="rgba(250,247,241,0.12)" strokeWidth="1" />
          <line x1={cx - hub} y1={cy} x2={cx + hub} y2={cy} stroke="rgba(250,247,241,0.07)" strokeWidth="0.8" />
          <line x1={cx} y1={cy - hub} x2={cx} y2={cy + hub} stroke="rgba(250,247,241,0.07)" strokeWidth="0.8" />
          <circle cx={cx} cy={cy} r={3} fill="rgba(250,247,241,0.3)" />
        </g>
      </svg>
    </div>
  );
}

function HomeHero({ setRoute }) {
  return (
    <section className="q-home-hero">
      <SiteNav route="home" setRoute={setRoute} theme="dark" />
      <div className="q-wrap q-home-hero-body">
        <div className="q-home-hero-grid">
          <div>
            <div className="q-eyebrow q-eyebrow--dark">Quarterdeck — AI · Strategy · Technology</div>
            <h1>
              <em>Seriously technical.</em> <span style={{ fontStyle: 'italic' }}>Genuinely strategic.</span>
            </h1>
            <p className="lede">
              We're AI-native, partner-led, and fluent across strategy and technology in a way that is genuinely uncommon.
            </p>
            <div className="q-home-hero-actions">
              <a className="qbtn qbtn--paper" href="mailto:info@quarterdeck.io">
                Start a conversation <Arrow />
              </a>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: '100%', maxWidth: 420 }}>
              <CompassWidget setRoute={setRoute} />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomeProposition() {
  return (
    <section className="q-prop-band">
      <div className="q-wrap">
        <div className="q-eyebrow">Our approach</div>
        <div className="q-prop-statement" style={{ marginTop: 20 }}>
          Technology — and now AI — is one of the most powerful levers an organization can pull. <em>Strategy is what determines whether you pull it well.</em>
        </div>
        <div className="q-prop-grid">
          <div className="q-prop-col">
            <p>We build with AI every day, for our clients and for ourselves. That fluency reaches every engagement: AI adoption for foundations and nonprofits, institutional intelligence and digital platforms for universities, custom automation for businesses ready to operate differently. Most firms treat strategy and technology as separate disciplines and staff them separately. We don't, because the best work doesn't allow for that separation. The thinking and the building happen together, with the same senior team, from the first conversation to the last deploy.</p>
          </div>
          <div className="q-prop-col">
            <p>The organizations that work best with us need a partner who can think rigorously about what to build and has the depth to actually build it. We work across foundations, higher education, nonprofits, and businesses, bringing that combination to every engagement. We work in sectors underserved by generalist consulting and equally underserved by technology vendors who execute without asking hard questions. That gap is the reason we exist, and the reason the work tends to be more interesting here than anywhere else.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomeServices({ setRoute }) {
  const services = [
    { num: '01', title: 'AI Adoption', route: 'ai-adoption', copy: "The highest-leverage workflows identified, the right tools built, the team trained. We map where AI can move the needle, build what's needed, and measure by whether adoption holds — not by whether training happened." },
    { num: '02', title: 'Strategy', route: 'strategy', copy: 'Senior counsel for the decisions that shape what comes next — organizational direction, technology strategy, funding models, positioning. Scoped to the actual question. Produced in writing. Actionable without a follow-on engagement to interpret it.' },
    { num: '03', title: 'Technology', route: 'technology', copy: 'Websites, digital infrastructure, data systems, custom software, and workflow automation. Built by people who asked the strategic questions first and are accountable for the result after launch.' },
  ];
  return (
    <section className="q-svc-overview">
      <div className="q-wrap">
        <div className="q-section-head">
          <div className="q-eyebrow">What we do</div>
          <h2>Strategy, technology, and AI adoption — <em>handled by the same team from start to finish.</em></h2>
          <p>The work spans three practice areas. In practice, most engagements touch more than one.</p>
        </div>
        <div className="q-svc-rows">
          {services.map(s => (
            <div key={s.num} className="q-svc-row" onClick={() => setRoute(s.route)}>
              <div className="num">{s.num}</div>
              <h3>{s.title}</h3>
              <p>{s.copy}</p>
              <Chevron />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeSegments({ setRoute }) {
  const segs = [
    {
      key: 'foundations', label: 'Foundations', Illo: IlloFoundations,
      copy: "Independent and community foundations navigating AI adoption, technology infrastructure, and the strategic questions that sit outside their existing advisory relationships."
    },
    {
      key: 'higher-ed', label: 'Higher Education', Illo: IlloHigherEd,
      copy: "Colleges, universities, and academic centers navigating institutional intelligence, digital infrastructure, and strategic questions that don't have easy internal answers."
    },
    {
      key: 'business', label: 'Business', Illo: IlloBusiness,
      copy: 'Operationally complex businesses ready to invest in AI, automation, and digital infrastructure — and looking for a partner who thinks before they build.'
    },
    {
      key: 'nonprofits', label: 'Non-Profits', Illo: IlloNonprofits,
      copy: 'Serious, operationally complex nonprofits with national or significant regional scope — organizations with real resources and real complexity, ready to close the gap on technology and AI.'
    },
  ];
  return (
    <section className="q-segments">
      <div className="q-wrap">
        <div className="q-section-head">
          <div className="q-eyebrow q-eyebrow--dark">Who we serve</div>
          <h2>The same problems appear across sectors. <em>The context is what changes.</em></h2>
          <p>We follow the problem, not just the industry. The strategic and technical challenges facing a national nonprofit and a regional university have more in common than the org charts would suggest.</p>
        </div>
        <div className="q-seg-grid">
          {segs.map((s, i) => (
            <div key={s.key} className="q-seg-card" onClick={() => setRoute(s.key)}>
              <div className="q-seg-illo"><s.Illo /></div>
              <div className="q-seg-body">
                <div className="q-seg-label">{String(i+1).padStart(2,'0')}</div>
                <h3>{s.label}</h3>
                <p>{s.copy}</p>
              </div>
              <a className="qlink qlink--on-dark">Read more <Arrow /></a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeWork({ setRoute }) {
  const items = [
    { yr: '2025', caseId: 'nec',        title: 'New England Conservatory', seg: 'Higher Education', body: 'Multi-year digital transformation: full platform rebuild with custom development and proprietary tooling. 2025 CASE Circle of Excellence Award.',        thumb: 'assets/nec-hero.jpg' },
    { yr: '2024', caseId: 'revere',     title: 'Revere Auctions',          seg: 'Business',         body: 'Five-year technical partnership: ground-up web platform and proprietary AI systems for specialized item identification and processing.', thumb: 'assets/Revere%20-%20Case%20Study%20Hero%20Image.jpg' },
    { yr: '2023', caseId: 'hazelden',   title: 'Hazelden Betty Ford Foundation', seg: 'Foundations', body: 'Reimagining lifelong recovery and alumni engagement for one of the most trusted names in addiction treatment.', thumb: 'assets/hazelden-hero.jpg' },
    { yr: '2024', caseId: 'edexchange', title: 'EdExchange',               seg: 'Higher Education', body: 'Sustainability and growth strategy for a nationally recognized education research platform at the Annenberg Institute at Brown.', thumb: 'assets/EdExchange%20Annenberg%20Brown%20-%20Case%20Study%20Hero%20Image.jpg' },
    { yr: '2023', caseId: 'ncare',      title: 'NCARE at Northwestern',    seg: 'Higher Education', body: 'New organizational strategy, funding model, and go-to-market approach at a critical inflection point.',                thumb: 'assets/Ncare%20-%20Case%20Study%20Hero%20Image.jpg' },
  ];
  const goCase = (caseId) => setRoute('case', caseId);
  return (
    <section className="q-work-sel">
      <div className="q-wrap">
        <div className="q-section-head">
          <div className="q-eyebrow">Selected work</div>
          <h2>Work we're proud of, <em>with clients we're grateful for.</em></h2>
          <p>Every engagement here was a real partnership — organizations that brought us into something that mattered to them, and trusted us to help figure it out.</p>
        </div>
        <div className="q-work-list">
          {items.map(i => (
            <div key={i.title} className="q-work-item" onClick={() => goCase(i.caseId)}>
              <div className="q-work-thumb" style={{ backgroundImage: `url(${i.thumb})` }} aria-hidden="true" />
              <h4>{i.title}<span className="seg">{i.seg}</span></h4>
              <p>{i.body}</p>
              <Chevron />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeLogos() {
  const clients = [
    { n: 'New England Conservatory', s: false },
    { n: 'Northwestern University', s: false },
    { n: 'Brown University', s: false },
    { n: 'Harvard Business School', s: false },
    { n: 'Revere Auctions', s: false },
    { n: 'Concord Academy', s: false },
    { n: 'Hazelden Betty Ford', s: false },
    { n: "The Women's Edge", s: false },
    { n: 'Hope Chicago', s: false },
    { n: 'REDF', s: false },
    { n: 'Turner Broadcasting', s: false },
    { n: 'KVC Builders', s: false },
  ];
  return (
    <section className="q-logos">
      <div className="q-wrap">
        <div className="q-logos-label">A partial list of clients</div>
        <div className="q-logos-grid">
          {clients.map(c => (
            <div key={c.n} className={'q-logo-mark' + (c.s ? ' q-logo-mark--sans' : '')}>{c.n}</div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeCloser({ setRoute }) {
  return (
    <section className="q-closer">
      <div className="q-wrap">
        <div className="q-closer-inner">
          <div>
            <div className="q-eyebrow">Start the conversation</div>
            <h2>Tell us what you are <em>trying to figure out.</em></h2>
          </div>
          <div>
            <p>The first conversation is twenty minutes, specific, and free. We'll ask about your organization before we suggest anything. If we're the right fit, we scope a first engagement in writing before you commit to anything.</p>
            <div style={{ marginTop: 28, display: 'flex', gap: 14, flexWrap: 'wrap' }}>
              <a className="qbtn qbtn--primary" href="mailto:info@quarterdeck.io">Email info@quarterdeck.io <Arrow /></a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomePage({ setRoute }) {
  return (
    <div data-screen-label="01 Home">
      <HomeHero setRoute={setRoute} />
      <HomeProposition />
      <HomeServices setRoute={setRoute} />
      <HomeSegments setRoute={setRoute} />
      <HomeWork setRoute={setRoute} />
      <HomeLogos />
      <HomeCloser setRoute={setRoute} />
      <SiteFooter setRoute={setRoute} />
    </div>
  );
}

Object.assign(window, { HomePage });
