// v3-mindmodel.jsx — S6 "One mind, connected to your whole world."
// Answers the reader's question after S5 ("so how does it know about me?").
//   Left  : a constellation — the Cortex orb at centre with the 6 lobes of
//           Lantic's mental model around it, beams flowing inward.
//   Right : a spotlight panel showing the ACTIVE lobe — what feeds it (clean
//           text chips). The active lobe AUTO-ROTATES (work → money → …) so the
//           reader sees every lobe without scrolling; tapping a lobe (or a dot)
//           takes over and the spotlight updates in place. Goals + Notes are
//           merged into a single "Memory" lobe.

const {
  BRAND, SAT, SF, MONO,
  useReducedMotion, useInView, useViewport,
  Cortex,
} = window;

// The six lobes. kind drives the small descriptor: tools you connect, people
// around you, or Lantic's own running memory of you.
const MIND_LOBES = [
  { id: 'work',   label: 'WORK',   col: '#38BDF8', kind: 'Apps & tools',
    line: 'Reads your email, calendar, jobs and customers, then acts on them.',
    chips: ['Google', 'Microsoft', 'Tradify', 'ServiceM8', 'Jobber', 'HubSpot', 'Shopify'] },
  { id: 'money',  label: 'MONEY',  col: '#10B981', kind: 'Apps & tools',
    line: 'Watches cash flow, chases what’s owed, sees every dollar in and out.',
    chips: ['Xero', 'MYOB', 'Square', 'Basiq'] },
  { id: 'team',   label: 'TEAM',   col: '#7DD3FC', kind: 'People',
    line: 'Sorts cover and schedules with your staff’s Lantics. No calls needed.',
    chips: ['Your staff', 'Their Lantics'] },
  { id: 'family', label: 'FAMILY', col: '#FB923C', kind: 'People',
    line: 'Protects the dinners, the games, the time that’s theirs.',
    chips: ['Your family’s Lantics', 'Shared calendar'] },
  { id: 'health', label: 'HEALTH', col: '#F472B6', kind: 'Apps & tools',
    line: 'Holds the gym slot, the early walk, the break you keep skipping.',
    chips: ['Calendar', 'Reminders'] },
  { id: 'memory', label: 'MEMORY', col: '#A78BFA', kind: 'Remembers',
    line: 'You mention it once. Lantic writes it down and brings it back at exactly the right moment.',
    chips: ['Your goals', 'Offhand notes', 'What you said last week'] },
];

// One-time keyframes.
if (typeof document !== 'undefined' && !document.getElementById('mm-kf')) {
  const s = document.createElement('style'); s.id = 'mm-kf';
  s.textContent = `
    @keyframes mm-flow { to { stroke-dashoffset: -24; } }
    @keyframes mm-orbpulse { 0%,100%{ transform: translate(-50%,-50%) scale(1); } 50%{ transform: translate(-50%,-50%) scale(1.03); } }
    @keyframes mm-cardin { from { opacity: 0; transform: translateY(9px); } to { opacity: 1; transform: none; } }
  `;
  document.head.appendChild(s);
}

// ─────────────────────────────────────────────────────────────────
// A single integration / source chip.
// ─────────────────────────────────────────────────────────────────
function SourceChip({ label, col }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '8px 13px', borderRadius: 10,
      fontFamily: SF, fontSize: 13.5, fontWeight: 500, letterSpacing: -0.1,
      whiteSpace: 'nowrap',
      background: `${col}1f`,
      border: `1px solid ${col}66`,
      color: BRAND.ink,
    }}>{label}</span>
  );
}

// ─────────────────────────────────────────────────────────────────
// Spotlight — the detail panel for the active lobe. Sits beside the
// constellation (below it on mobile) so what you tap is instantly in view.
// ─────────────────────────────────────────────────────────────────
function Spotlight({ lobe, order, active, onPick, phone }) {
  return (
    <div style={{
      position: 'relative', borderRadius: 22,
      padding: phone ? '24px 22px' : '34px 34px',
      background: `linear-gradient(158deg, ${lobe.col}22 0%, rgba(255,255,255,.03) 72%)`,
      border: `1px solid ${lobe.col}66`,
      boxShadow: `0 30px 80px -38px ${lobe.col}aa`,
      transition: 'border-color 450ms ease, box-shadow 450ms ease, background 450ms ease',
      minHeight: phone ? 'auto' : 300,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* content re-keyed on the active lobe so it re-animates on each change */}
      <div key={lobe.id} style={{ animation: 'mm-cardin 480ms cubic-bezier(.22,1,.36,1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
          <span style={{ width: 10, height: 10, borderRadius: 5, background: lobe.col, flex: '0 0 auto',
            boxShadow: `0 0 14px ${lobe.col}` }}/>
          <span style={{ fontFamily: MONO, fontSize: 13, color: lobe.col,
            letterSpacing: '0.22em', fontWeight: 700 }}>{lobe.label}</span>
          <span style={{ fontFamily: MONO, fontSize: 9.5, color: BRAND.dim,
            letterSpacing: '0.18em', fontWeight: 600, textTransform: 'uppercase',
            marginLeft: 'auto', padding: '4px 9px', borderRadius: 7,
            background: 'rgba(255,255,255,.05)', border: '1px solid rgba(255,255,255,.09)' }}>{lobe.kind}</span>
        </div>
        <div style={{ fontFamily: SAT, fontWeight: 500, fontSize: phone ? 19 : 23,
          lineHeight: 1.32, letterSpacing: -0.6, color: BRAND.ink, textWrap: 'pretty' }}>{lobe.line}</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 22 }}>
          {lobe.chips.map(c => <SourceChip key={c} label={c} col={lobe.col}/>)}
        </div>
      </div>

      {/* rotation dots — show progress through the lobes and let you jump */}
      <div style={{ marginTop: 'auto', paddingTop: 26, display: 'flex', gap: 8, alignItems: 'center' }}>
        {order.map(id => {
          const o = MIND_LOBES.find(l => l.id === id);
          const on = id === active;
          return (
            <button key={id} onClick={() => onPick(id)} aria-label={o.label} style={{
              width: on ? 24 : 8, height: 8, borderRadius: 6, padding: 0, border: 'none', cursor: 'pointer',
              background: on ? o.col : 'rgba(255,255,255,.18)',
              boxShadow: on ? `0 0 10px ${o.col}` : 'none',
              transition: 'all 360ms cubic-bezier(.22,1,.36,1)',
            }}/>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Section
// ─────────────────────────────────────────────────────────────────
function MindModel() {
  const ref = React.useRef(null);
  const inView = useInView(ref, 0.16);
  const reduced = useReducedMotion();
  const vw = useViewport();
  const phone = vw < 640;
  const compact = vw < 1024;

  const order = MIND_LOBES.map(l => l.id);
  const [active, setActive] = React.useState('work');
  const [paused, setPaused] = React.useState(false);
  const resumeRef = React.useRef(null);

  // user takes over: select + pause auto-rotate, then resume after idle.
  const pick = (id) => {
    setActive(id);
    setPaused(true);
    clearTimeout(resumeRef.current);
    resumeRef.current = setTimeout(() => setPaused(false), 9000);
  };

  // auto-rotate the active lobe while the section is in view.
  React.useEffect(() => {
    if (!inView || paused || reduced) return;
    const t = setInterval(() => {
      setActive(prev => order[(order.indexOf(prev) + 1) % order.length]);
    }, 3200);
    return () => clearInterval(t);
  }, [inView, paused, reduced]);
  React.useEffect(() => () => clearTimeout(resumeRef.current), []);

  // Ring geometry — nodes evenly spaced, starting at the top.
  const N = MIND_LOBES.length;
  const radius = phone ? 40 : 39;
  const pts = MIND_LOBES.map((l, i) => {
    const a = (-90 + i * (360 / N)) * Math.PI / 180;
    return { ...l, x: 50 + radius * Math.cos(a), y: 50 + radius * Math.sin(a) };
  });
  const activeLobe = MIND_LOBES.find(l => l.id === active) || MIND_LOBES[0];

  return (
    <section ref={ref} id="mind" data-screen-label="mental-model" style={{
      position: 'relative', padding: phone ? '96px 20px 104px' : compact ? '120px 28px 132px' : '150px 32px 168px',
      background: BRAND.canvasDeep, overflow: 'hidden',
    }}>
      {/* ambient glow, tinted to the active lobe */}
      <div aria-hidden style={{ position: 'absolute', inset: 0, pointerEvents: 'none', transition: 'background 600ms ease',
        background: `radial-gradient(ellipse 52% 46% at 50% 30%, ${activeLobe.col}22 0%, transparent 62%)` }}/>

      <div style={{ position: 'relative', maxWidth: 1120, margin: '0 auto' }}>
        {/* Header */}
        <div style={{ textAlign: 'center', maxWidth: 780, margin: '0 auto' }}>
          <div style={{ fontFamily: MONO, fontSize: 11, color: BRAND.skyMist,
            letterSpacing: '0.28em', fontWeight: 600, textTransform: 'uppercase', marginBottom: 22 }}>
            How it knows you
          </div>
          <h2 style={{ margin: 0, fontFamily: SAT, fontWeight: 600,
            fontSize: phone ? 'clamp(33px,7.6vw,44px)' : 'clamp(44px,4.4vw,66px)',
            letterSpacing: -2.4, lineHeight: 1.03, color: BRAND.ink, textWrap: 'balance' }}>
            One mind, connected to<br/>your whole world.
          </h2>
          <div style={{ marginTop: 22, fontFamily: SF, fontSize: phone ? 16 : 18.5,
            lineHeight: 1.55, letterSpacing: -0.2, color: BRAND.sub,
            maxWidth: 640, margin: '22px auto 0', textWrap: 'pretty' }}>
            Lantic connects to your world, the tools you already run on and the people
            around you, and keeps it all in one mind. {phone ? 'Tap' : 'Hover or tap'} a
            lobe to see what feeds it.
          </div>
        </div>

        {/* constellation + spotlight */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: compact ? '1fr' : 'minmax(0, 1fr) minmax(0, 1fr)',
          gap: phone ? 28 : 56, alignItems: 'center',
          marginTop: phone ? 40 : 70,
        }}>
          {/* Part A — constellation */}
          <div style={{ position: 'relative', width: '100%', maxWidth: phone ? 340 : 480,
            aspectRatio: '1 / 1', margin: '0 auto' }}>
            {/* beams */}
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible',
              opacity: inView ? 1 : 0, transition: 'opacity 900ms ease' }}>
              {pts.map(p => {
                const on = active === p.id;
                const col = on ? p.col : BRAND.skyLight;
                return (
                  <g key={p.id}>
                    <line x1={p.x} y1={p.y} x2="50" y2="50" stroke={col}
                      strokeOpacity={on ? 0.4 : 0.16} strokeWidth="1" vectorEffect="non-scaling-stroke"/>
                    <line x1={p.x} y1={p.y} x2="50" y2="50" stroke={col}
                      strokeOpacity={on ? 0.95 : 0.5} strokeWidth={on ? 1.6 : 1.1}
                      strokeDasharray="3 9" strokeLinecap="round" vectorEffect="non-scaling-stroke"
                      style={{ filter: `drop-shadow(0 0 3px ${col})`,
                        animation: reduced ? 'none' : `mm-flow ${on ? 1 : 2}s linear infinite`,
                        transition: 'stroke 400ms ease, stroke-opacity 400ms ease' }}/>
                  </g>
                );
              })}
            </svg>

            {/* centre orb */}
            <div style={{ position: 'absolute', left: '50%', top: '50%', zIndex: 2,
              transform: 'translate(-50%,-50%)',
              animation: reduced ? 'none' : 'mm-orbpulse 5.5s ease-in-out infinite' }}>
              <Cortex size={phone ? 92 : 122} animate={inView && !reduced}
                glowLobe={activeLobe.col} glowAlpha={0.82}/>
            </div>

            {/* lobe nodes */}
            {pts.map((p, i) => {
              const on = active === p.id;
              return (
                <button key={p.id}
                  onClick={() => pick(p.id)}
                  onMouseEnter={() => !phone && pick(p.id)}
                  style={{
                    position: 'absolute', left: `${p.x}%`, top: `${p.y}%`, zIndex: 3,
                    transform: `translate(-50%,-50%) scale(${inView ? (on ? 1.08 : 1) : 0.6})`,
                    opacity: inView ? 1 : 0,
                    transition: `opacity 600ms ease ${i * 70}ms, transform 500ms cubic-bezier(.22,1,.36,1), background 260ms ease, border-color 260ms ease, box-shadow 260ms ease`,
                    display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                    padding: phone ? '7px 11px' : '9px 14px', borderRadius: 99, font: 'inherit',
                    background: on ? `${p.col}26` : 'rgba(9,14,26,.78)',
                    border: `1px solid ${on ? p.col : 'rgba(255,255,255,.13)'}`,
                    boxShadow: on ? `0 0 26px ${p.col}88` : '0 6px 18px rgba(5,11,23,.5)',
                    backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', whiteSpace: 'nowrap',
                  }}>
                  <span style={{ width: 7, height: 7, borderRadius: 4, background: p.col, flex: '0 0 auto',
                    boxShadow: `0 0 10px ${p.col}` }}/>
                  <span style={{ fontFamily: MONO, fontSize: phone ? 10 : 11.5, fontWeight: 700,
                    letterSpacing: '0.18em', color: on ? '#fff' : BRAND.sub }}>{p.label}</span>
                </button>
              );
            })}
          </div>

          {/* Part B — spotlight (updates as it rotates / on tap) */}
          <Spotlight lobe={activeLobe} order={order} active={active} onPick={pick} phone={phone}/>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { MindModel });
