/* ──────────────────────────────────────────────────────────
   "What We Do" + "MATAI Framework" — split into two sections
   (each its own component, exported separately).
   ────────────────────────────────────────────────────────── */
const { useState, useEffect, useRef } = React;

/* Simple inline icons for the framework rail */
function StackIconSimple({ size = 32 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none">
      <path d="M 24 8 L 38 16 L 24 24 L 10 16 Z" stroke="var(--ink)" strokeWidth="1.2" fill="rgba(184,153,104,0.12)"/>
      <path d="M 10 24 L 24 32 L 38 24" stroke="var(--ink)" strokeWidth="1.2" fill="none"/>
      <path d="M 10 32 L 24 40 L 38 32" stroke="var(--gold)" strokeWidth="1.2" fill="none"/>
    </svg>
  );
}

function CompassFrameworkIcon({ size = 32 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none">
      <circle cx="24" cy="24" r="14" stroke="var(--ink)" strokeWidth="1.2"/>
      <path d="M 24 12 L 26 24 L 24 36 L 22 24 Z" fill="var(--gold)" stroke="var(--ink)" strokeWidth="0.6"/>
      <circle cx="24" cy="24" r="1.5" fill="var(--ink)"/>
    </svg>
  );
}

function CubeFrameworkIcon({ size = 32 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none">
      <path d="M 24 6 L 38 14 L 38 32 L 24 40 L 10 32 L 10 14 Z"
        fill="var(--gold)" stroke="var(--ink)" strokeWidth="0.8"/>
      <path d="M 24 6 L 24 22 L 38 30" stroke="var(--ink)" strokeWidth="0.6" opacity="0.45"/>
      <path d="M 24 22 L 10 30" stroke="var(--ink)" strokeWidth="0.6" opacity="0.45"/>
    </svg>
  );
}

function ChartFrameworkIcon({ size = 32 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none">
      <rect x="8" y="28" width="6" height="14" fill="var(--ink)" rx="1"/>
      <rect x="18" y="20" width="6" height="22" fill="var(--ink)" rx="1"/>
      <rect x="28" y="14" width="6" height="28" fill="var(--gold)" rx="1"/>
      <path d="M 8 18 L 18 14 L 28 10 L 38 6" stroke="var(--gold-deep)" strokeWidth="1.2" fill="none" strokeLinecap="round"/>
      <path d="M 36 4 L 40 6 L 38 10" stroke="var(--gold-deep)" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ──────────────────────────────────────────────────────────
   What We Do — three service cards with custom PNG icons,
   no numbers, no clickable arrows.
   ────────────────────────────────────────────────────────── */
function ServiceCard({ s, delay = 0 }) {
  const [hover, setHover] = useState(false);
  return (
    <Reveal delay={delay}>
      <div
        onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
        style={{
          position:'relative', padding:'30px 36px', borderRadius:'18px',
          background:'var(--paper)', border:'1px solid var(--line)',
          display:'grid', gridTemplateColumns:'220px 1fr',
          alignItems:'center', gap:'32px', minHeight:'200px',
          transition:'transform .35s cubic-bezier(.2,.7,.2,1), box-shadow .35s, border-color .35s',
          transform: hover ? 'translateY(-3px)' : 'translateY(0)',
          boxShadow: hover ? '0 24px 48px -20px rgba(20,24,31,0.14)' : 'none',
          borderColor: hover ? 'var(--gold)' : 'var(--line)',
        }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'center' }}>
          <img src={s.icon} alt=""
            style={{ width:'200px', height:'200px', objectFit:'contain',
              userSelect:'none' }}
            draggable={false} />
        </div>
        <div>
          <div style={{ fontFamily:"'Bodoni Moda', serif", fontWeight:300,
            fontSize:'26px', lineHeight:1.12, letterSpacing:'-0.01em',
            color:'var(--ink)', marginBottom:'14px', textWrap:'balance' }}>
            {s.title}
          </div>
          <div style={{ width:'28px', height:'1px', background:'var(--gold)',
            marginBottom:'16px' }} />
          <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'14px',
            color:'var(--ink-2)', lineHeight:1.7, maxWidth:'460px' }}>{s.desc}</p>
        </div>
      </div>
    </Reveal>
  );
}

function WhatWeDoSection() {
  const isMobile = useIsMobile();
  const [openIdx, setOpenIdx] = useState(null);
  const services = [
    { title:'Agentic AI Strategy Development', icon:'assets/icon-strategy.png',
      desc:'We help you define a clear AI strategy aligned to your business goals, identify high-impact opportunities, and create a roadmap for success.' },
    { title:'AI Implementation', icon:'assets/icon-implementation.png',
      desc:'We design and build secure, scalable AI systems that integrate seamlessly with your workflows and deliver measurable business value.' },
    { title:'Training, Support & Maintenance', icon:'assets/icon-training.png',
      desc:'We equip your teams, monitor performance, and provide ongoing support to ensure your AI systems continue to evolve and perform.' },
  ];

  if (isMobile) {
    return (
      <section id="services" data-theme="light" data-screen-label="what-we-do" style={{
        padding:'72px 24px 64px', background:'var(--bg)',
      }}>
        {/* Header */}
        <Reveal style={{ marginBottom:'40px' }}>
          <Eyebrow tone="gold" style={{ marginBottom:'18px' }}>What We Do</Eyebrow>
          <h2 style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14", fontWeight:500,
            fontSize:'clamp(34px, 9vw, 50px)', lineHeight:1.06,
            letterSpacing:'-0.025em', marginBottom:'20px', color:'var(--ink)' }}>
            Turning Agentic AI Potential into{' '}
            <span className="accent-italic">Business Results</span>
          </h2>
          <div style={{ width:'40px', height:'1px', background:'var(--gold)', marginBottom:'18px' }} />
          <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'15px',
            color:'var(--ink-2)', lineHeight:1.75 }}>
            From strategy and governance to architecture and execution, we help
            organizations move beyond experimentation and scale AI with confidence.
          </p>
        </Reveal>

        {/* Accordion */}
        <div style={{ display:'flex', flexDirection:'column', gap:'0',
          border:'1px solid var(--line)', borderRadius:'16px', overflow:'hidden' }}>
          {services.map((s, i) => {
            const open = openIdx === i;
            return (
              <div key={i} style={{ borderTop: i > 0 ? '1px solid var(--line)' : 'none' }}>
                <button onClick={() => setOpenIdx(open ? null : i)}
                  style={{ width:'100%', background:'none', border:'none', cursor:'pointer',
                    padding:'18px 20px', display:'flex', alignItems:'center',
                    gap:'16px', textAlign:'left' }}>
                  <img src={s.icon} alt="" style={{ width:'52px', height:'52px',
                    objectFit:'contain', flexShrink:0 }} draggable={false} />
                  <div style={{ flex:1, fontFamily:"'Bodoni Moda', serif",
                    fontVariationSettings:"'opsz' 14", fontWeight:400,
                    fontSize:'18px', color:'var(--ink)', lineHeight:1.2,
                    letterSpacing:'-0.01em' }}>
                    {s.title}
                  </div>
                  <span style={{ flexShrink:0, width:'24px', height:'24px',
                    borderRadius:'50%', border:'1px solid var(--gold)',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    color:'var(--gold-deep)', fontSize:'16px', fontWeight:300,
                    transition:'transform .3s',
                    transform: open ? 'rotate(45deg)' : 'none' }}>
                    +
                  </span>
                </button>
                <div style={{ display:'grid',
                  gridTemplateRows: open ? '1fr' : '0fr',
                  transition:'grid-template-rows .4s cubic-bezier(.4,0,.2,1)' }}>
                  <div style={{ overflow:'hidden' }}>
                    <div style={{ padding:'0 20px 22px', paddingLeft:'88px',
                      opacity: open ? 1 : 0,
                      transition:'opacity .3s ease', transitionDelay: open ? '.1s' : '0s' }}>
                      <div style={{ width:'28px', height:'1px', background:'var(--gold)',
                        marginBottom:'14px' }} />
                      <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'14px',
                        color:'var(--ink-2)', lineHeight:1.7 }}>{s.desc}</p>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </section>
    );
  }

  return (
    <section id="services" data-theme="light" data-screen-label="what-we-do" style={{
      padding:'140px 40px 110px', background:'var(--bg)',
    }}>
      <div style={{ maxWidth:'1320px', margin:'0 auto' }}>
        <div style={{ display:'grid', gridTemplateColumns:'0.85fr 1.15fr', gap:'60px',
          alignItems:'start' }}>
          <Reveal>
            <Eyebrow tone="gold" style={{ marginBottom:'22px' }}>What We Do</Eyebrow>
            <h2 style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14", fontWeight:500,
              fontSize:'clamp(38px, 4.6vw, 60px)', lineHeight:1.06,
              letterSpacing:'-0.025em', marginBottom:'26px', color:'var(--ink)',
              textWrap:'balance' }}>
              Turning Agentic AI Potential into{' '}
              <span className="accent-italic">Business Results</span>
            </h2>
            <div style={{ width:'48px', height:'1px', background:'var(--gold)', marginBottom:'26px' }} />
            <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'15.5px',
              color:'var(--ink-2)', lineHeight:1.75, maxWidth:'380px' }}>
              From strategy and governance to architecture and execution, we help
              organizations move beyond experimentation and scale AI with confidence.
            </p>
          </Reveal>

          <div style={{ display:'flex', flexDirection:'column', gap:'18px' }}>
            {services.map((s, i) => <ServiceCard key={i} s={s} delay={i * 0.08} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────────────────
   MATAI Framework — its own section, horizontal phase rail
   ────────────────────────────────────────────────────────── */
function FrameworkSection() {
  const phases = [
    { n:'01', t:'Discover', d:'We assess your AI maturity, data readiness, and opportunities to identify where AI can create the most value.', Icon: CompassFrameworkIcon },
    { n:'02', t:'Design',   d:'We architect your roadmap and solution blueprints aligned to your goals—grounded in the MATAI Framework.', Icon: StackIconSimple },
    { n:'03', t:'Deploy',   d:'We build and integrate custom solutions that move from prototype to production with speed and precision.', Icon: CubeFrameworkIcon },
    { n:'04', t:'Scale',    d:'We optimize, measure, and evolve your systems to continuously improve performance and drive long-term impact.', Icon: ChartFrameworkIcon },
  ];

  return (
    <section id="framework" data-theme="light" data-screen-label="framework" style={{
      padding:'120px 40px 130px', background:'var(--bg)',
      borderTop:'1px solid var(--line-2)', borderBottom:'1px solid var(--line-2)',
    }}>
      <div style={{ maxWidth:'1320px', margin:'0 auto' }}>
        <div style={{ display:'grid', gridTemplateColumns:'0.85fr 1.15fr', gap:'60px',
          alignItems:'start', marginBottom:'80px' }}>
          <Reveal>
            <Eyebrow tone="gold" style={{ marginBottom:'22px' }}>Our Approach</Eyebrow>
            <h2 style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14", fontWeight:500,
              fontSize:'clamp(44px, 5.4vw, 70px)', lineHeight:1.0,
              letterSpacing:'-0.025em', marginBottom:'26px', color:'var(--ink)' }}>
              The MATAI<br/><span className="accent-italic">Framework.</span>
            </h2>
            <div style={{ width:'48px', height:'1px', background:'var(--gold)',
              marginBottom:'26px' }} />
            <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'15.5px',
              color:'var(--ink-2)', lineHeight:1.75, maxWidth:'380px', marginBottom:'30px' }}>
              A proven, end-to-end approach that turns strategy into scalable,
              real-world impact.
            </p>
            <a href="#contact" style={{
              display:'inline-flex', alignItems:'center', gap:'12px',
              fontFamily:"'Inter',sans-serif", fontWeight:500, fontSize:'14px',
              letterSpacing:'0.02em', textDecoration:'none', color:'var(--ink)',
            }}>
              <span style={{
                width:'40px', height:'40px', borderRadius:'50%',
                background:'transparent', border:'1px solid var(--gold)',
                display:'inline-flex', alignItems:'center', justifyContent:'center',
                color:'var(--gold-deep)', fontSize:'12px',
              }}>▶</span>
              Explore the framework
            </a>
          </Reveal>

          <Reveal delay={0.1}>
            <div style={{ display:'grid',
              gridTemplateColumns:'1fr auto 1fr auto 1fr auto 1fr',
              alignItems:'start', gap:'14px' }}>
              {phases.map((p, i) => (
                <React.Fragment key={p.n}>
                  <div style={{ display:'flex', flexDirection:'column', alignItems:'center',
                    textAlign:'center', gap:'12px' }}>
                    <div style={{ width:'66px', height:'66px', borderRadius:'50%',
                      border:'1px solid var(--line)', background:'var(--paper)',
                      display:'flex', alignItems:'center', justifyContent:'center' }}>
                      <p.Icon size={30} />
                    </div>
                    <div style={{ fontFamily:"'Bodoni Moda', serif", fontSize:'12px', fontWeight:300,
                      color:'var(--gold-deep)', letterSpacing:'0.14em', marginTop:'4px' }}>{p.n}</div>
                    <div style={{ fontFamily:"'Bodoni Moda', serif", fontSize:'24px', fontWeight:300,
                      color:'var(--ink)', letterSpacing:'-0.005em' }}>{p.t}</div>
                    <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'12.5px',
                      color:'var(--ink-2)', lineHeight:1.6, maxWidth:'180px', marginTop:'2px' }}>{p.d}</p>
                  </div>
                  {i < phases.length - 1 && (
                    <div style={{ display:'flex', alignItems:'center', justifyContent:'center',
                      paddingTop:'30px', color:'var(--gold)', fontSize:'20px',
                      fontFamily:"'Bodoni Moda', serif" }}>›</div>
                  )}
                </React.Fragment>
              ))}
            </div>
          </Reveal>
        </div>

        <Reveal>
          <div style={{ padding:'22px 32px', background:'var(--paper)',
            border:'1px solid var(--line)', borderRadius:'14px',
            display:'flex', alignItems:'center', justifyContent:'center', gap:'14px',
            fontFamily:"'Inter',sans-serif", fontSize:'14px', fontWeight:400,
            color:'var(--ink-2)', letterSpacing:'0.01em' }}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M 10 2 L 12 8 L 18 10 L 12 12 L 10 18 L 8 12 L 2 10 L 8 8 Z"
                fill="var(--gold)" stroke="var(--gold-deep)" strokeWidth="0.5"/>
            </svg>
            Built for the Agentic AI era. Focused on outcomes that matter.
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────────────────
   About Matai — left copy, right brand orbit visual.
   ────────────────────────────────────────────────────────── */
function AboutOrbit({ size }) {
  const gold = '#B89968', goldDeep = '#8A6F45';
  const cx = 200, cy = 200;
  const N = 9;
  // Stable particle definitions (don't recompute on re-render or the loop restarts).
  const parts = React.useMemo(() => Array.from({ length: N }, (_, i) => ({
    ang: (i / N) * Math.PI * 2,
    r: 64 + ((i * 41) % 92),            // varied orbit radii 64..152
    speed: 0.10 + ((i % 4) * 0.028),    // varied orbital speed
    side: i % 2 === 0 ? 1 : -1,         // which side of centre it aligns to
    rad: i % 3 === 0 ? 3.6 : 2.4,       // dot radius
    deep: i % 2 === 0,
  })), []);
  const dotsRef  = useRef([]);
  const lineRef  = useRef(null);
  const hoverRef = useRef(false);
  const progRef  = useRef(0);
  const [hovered, setHovered] = useState(false);

  useEffect(() => {
    const start = performance.now();
    let raf;
    const loop = (now) => {
      const t = (now - start) / 1000;
      const target = hoverRef.current ? 1 : 0;
      progRef.current += (target - progRef.current) * 0.07;      // ease toward target
      const e = progRef.current * progRef.current * (3 - 2 * progRef.current); // smoothstep
      const phi = t * 0.28;                                      // line angle — keeps rotating
      parts.forEach((pt, i) => {
        const orbitAng = pt.ang + t * pt.speed;                  // each star's own orbit angle
        const targetAng = phi + (pt.side < 0 ? Math.PI : 0);     // its slot on the rotating diameter
        let d = targetAng - orbitAng;
        d = Math.atan2(Math.sin(d), Math.cos(d));                // shortest way around the ring
        const ang = orbitAng + d * e;                            // travel ALONG the ring to the line
        const x = cx + Math.cos(ang) * pt.r;                     // radius preserved → stays on its orbit path
        const y = cy + Math.sin(ang) * pt.r;
        const el = dotsRef.current[i];
        if (el) { el.setAttribute('cx', x.toFixed(1)); el.setAttribute('cy', y.toFixed(1)); }
      });
      const ln = lineRef.current;                                // rotating alignment axis
      if (ln) {
        const R = 160;
        ln.setAttribute('x1', (cx - Math.cos(phi) * R).toFixed(1));
        ln.setAttribute('y1', (cy - Math.sin(phi) * R).toFixed(1));
        ln.setAttribute('x2', (cx + Math.cos(phi) * R).toFixed(1));
        ln.setAttribute('y2', (cy + Math.sin(phi) * R).toFixed(1));
      }
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [parts]);

  const onEnter = () => { hoverRef.current = true;  setHovered(true); };
  const onLeave = () => { hoverRef.current = false; setHovered(false); };

  return (
    <svg viewBox="0 0 400 400" width={size} height={size}
      onMouseEnter={onEnter} onMouseLeave={onLeave}
      style={{ display:'block', maxWidth:'100%' }}>
      <defs>
        <radialGradient id="aboutGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0" stopColor="#D9C29A" stopOpacity="0.18" />
          <stop offset="55%" stopColor="#D9C29A" stopOpacity="0.05" />
          <stop offset="100%" stopColor="#D9C29A" stopOpacity="0" />
        </radialGradient>
      </defs>
      <circle cx={cx} cy={cy} r="185" fill="url(#aboutGlow)" />

      {/* Orbit guide rings — always visible (the stars keep orbiting on them) */}
      <circle cx={cx} cy={cy} r="152" fill="none" stroke={gold} strokeWidth="0.7" opacity="0.42" />
      <circle cx={cx} cy={cy} r="108" fill="none" stroke={gold} strokeWidth="0.7" opacity="0.4" strokeDasharray="2 4" />
      <circle cx={cx} cy={cy} r="64"  fill="none" stroke={gold} strokeWidth="0.7" opacity="0.34" />

      {/* Rotating alignment axis — fades in on hover */}
      <line ref={lineRef} x1={cx} y1={cy} x2={cx} y2={cy} stroke={gold} strokeWidth="0.8"
        style={{ opacity: hovered ? 0.45 : 0, transition:'opacity .55s ease' }} />

      {parts.map((pt, i) => (
        <circle key={i} ref={el => dotsRef.current[i] = el} cx={cx} cy={cy} r={pt.rad}
          fill={pt.deep ? goldDeep : gold} />
      ))}
      <circle cx={cx} cy={cy} r="4.5" fill={goldDeep} />
    </svg>
  );
}

function AboutSection() {
  const isMobile = useIsMobile();
  const paras = [
    "Most organizations do not struggle with a lack of AI ideas. They struggle with turning those ideas into trusted, scalable business outcomes.",
    "Matai Consulting was founded to help organizations navigate the opportunities and challenges of the Agentic AI era. Combining enterprise transformation experience with proprietary methodologies, we help leaders assess readiness, develop effective strategies, and implement AI systems that are governed, trusted, and built for long-term adoption.",
    "We believe successful AI transformation requires more than technology. It requires alignment across strategy, governance, data, workflows, and organizational change.",
  ];

  return (
    <section id="about" data-theme="light" data-screen-label="about" style={{
      padding: isMobile ? '76px 24px 80px' : '92px 40px',
      background:'var(--bg)', borderTop:'1px solid var(--line-2)',
    }}>
      <div style={{ maxWidth:'1320px', margin:'0 auto', display:'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.05fr 0.95fr',
        gap: isMobile ? '44px' : '64px', alignItems:'center' }}>

        {/* Left — copy */}
        <Reveal>
          <Eyebrow tone="gold" style={{ marginBottom: isMobile ? '18px' : '22px' }}>About Matai</Eyebrow>
          <h2 style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14", fontWeight:500,
            fontSize: isMobile ? 'clamp(38px, 10.5vw, 56px)' : 'clamp(44px, 5vw, 76px)',
            lineHeight:1.02, letterSpacing:'-0.025em', color:'var(--ink)',
            marginBottom: isMobile ? '24px' : '30px', textWrap:'balance' }}>
            From AI ambition to AI <span className="accent-italic">adoption.</span>
          </h2>
          <div style={{ width:'48px', height:'1px', background:'var(--gold)', marginBottom:'28px' }} />
          {paras.map((p, i) => (
            <p key={i} style={{ fontFamily:"'Inter',sans-serif", fontWeight:300,
              fontSize:'15.5px', color:'var(--ink-2)', lineHeight:1.75,
              maxWidth:'540px', marginBottom:'18px' }}>{p}</p>
          ))}
          <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:600, fontSize:'16px',
            color:'var(--ink)', marginTop:'10px' }}>That’s where Matai comes in.</p>
        </Reveal>

        {/* Right — brand orbit visual */}
        <Reveal delay={0.1} style={{ display:'flex', justifyContent:'center', alignItems:'center' }}>
          <AboutOrbit size={isMobile ? Math.min(290, window.innerWidth * 0.7) : Math.min(400, window.innerWidth * 0.28)} />
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { WhatWeDoSection, FrameworkSection, AboutSection });
