// Hero — animated text cycle + container-scroll tilting card + interactive contract preview
const { useState, useEffect, useRef, useLayoutEffect, useCallback } = React;

const HERO_ROTATE = [
'made simple.',
'reviewed faster.',
'in plain English.',
'balanced.'];


// Mock contract clauses — hover/tap to see SubSync's flag
const CLAUSES = [
{
  id: 'c1',
  n: '14.2',
  title: 'Liability',
  text: 'The Subcontractor shall be liable to the Contractor for all losses, damages, costs and expenses howsoever suffered or incurred by the Contractor arising directly or indirectly out of or in connection with the Subcontractor\u2019s performance of the Works.',
  flag: {
    level: 'high',
    label: 'HIGH RISK',
    heading: 'No liability cap — uncapped exposure',
    detail: 'Industry norm is to cap liability at the contract value (sometimes 1.5×). As written, your exposure is unlimited.',
    ask: 'Cap aggregate liability at the Subcontract Sum and exclude consequential loss.'
  }
},
{
  id: 'c2',
  n: '22.1',
  title: 'Payment',
  text: 'Notwithstanding anything to the contrary, the Subcontractor shall not be entitled to payment of any amount until the Contractor has first received payment from the Principal of all amounts attributable to the Subcontract Works.',
  flag: {
    level: 'high',
    label: 'HIGH RISK',
    heading: 'Pay-when-paid trigger',
    detail: 'Conditioning your payment on the Principal paying the Contractor. This is void and unenforceable under SOPA in NSW, VIC and QLD.',
    ask: 'Strike this clause. Replace with a fixed payment date tied to claim submission.'
  }
},
{
  id: 'c5',
  n: '15.6',
  title: 'Indemnity',
  text: 'The Subcontractor shall indemnify and keep indemnified the Contractor against any and all claims, losses, damages, liabilities, costs and expenses (including legal costs on a full indemnity basis) arising out of or in connection with the Subcontract Works, however caused.',
  flag: {
    level: 'high',
    label: 'HIGH RISK',
    heading: 'Open-ended indemnity — “however caused”',
    detail: 'Forces you to indemnify the Contractor even where the loss is caused by the Contractor or a third party. Highly one-sided and uninsurable as drafted.',
    ask: 'Limit indemnity to losses caused by the Subcontractor’s negligence, and exclude losses caused by the Contractor or others.'
  }
},
{
  id: 'c3',
  n: '18.4',
  title: 'EOT notices',
  text: 'A claim for an extension of time must be made by the Subcontractor in writing within five (5) business days of the event giving rise to the delay, failing which the Subcontractor shall have no entitlement to an extension.',
  flag: {
    level: 'medium',
    label: 'MEDIUM RISK',
    heading: 'EOT notice window only 5 business days',
    detail: 'Tight. Industry standard is 10\u201314 business days. Time bars are strictly enforced — miss it and the claim dies.',
    ask: 'Negotiate to 10 business days minimum, and tie the window to when the delay is reasonably evident.'
  }
},
{
  id: 'c4',
  n: '9.3',
  title: 'Variations',
  text: 'The Contractor may direct variations to the Subcontract Works at any time. The Subcontractor shall be entitled to a reasonable adjustment to the Subcontract Sum and time for completion, assessed in accordance with the rates in the Schedule of Rates.',
  flag: {
    level: 'compliant',
    label: 'Ready for review',
    heading: 'Variation clause is fair',
    detail: 'Allows time and cost recovery on directed variations, with assessment tied to the agreed rates. No action needed.',
    ask: 'Accept as drafted.'
  }
}];


const LEVEL_STYLES = {
  high: { bg: '#ffe7e1', border: '#ffd0c4', text: '#8a1505', dot: '#ee2200', accent: '#ee2200' },
  medium: { bg: '#fef5d8', border: '#fbe39a', text: '#6b4d00', dot: '#fab515', accent: '#fab515' },
  compliant: { bg: '#e3f5e1', border: '#bce7b6', text: '#1a5a18', dot: '#69c765', accent: '#69c765' }
};

/* ───────── Animated text cycle (height-stable, blur fade) ───────── */
function AnimatedTextCycle({ words, interval = 3200 }) {
  const [i, setI] = useState(0);
  const [w, setW] = useState('auto');
  const measureRef = useRef(null);

  useLayoutEffect(() => {
    if (!measureRef.current) return;
    const el = measureRef.current.children[i];
    if (el) {
      const r = el.getBoundingClientRect();
      setW(`${Math.ceil(r.width)}px`);
    }
  }, [i]);

  useEffect(() => {
    const t = setInterval(() => setI((p) => (p + 1) % words.length), interval);
    return () => clearInterval(t);
  }, [interval, words.length]);

  return (
    <span className="inline-block align-baseline" style={{ position: 'relative' }}>
      {/* hidden measure */}
      <span
        ref={measureRef}
        aria-hidden="true"
        style={{ position: 'absolute', visibility: 'hidden', whiteSpace: 'nowrap', left: 0, top: 0 }}>
        
        {words.map((wd, idx) =>
        <span key={idx} style={{ fontWeight: 800 }}>{wd}</span>
        )}
      </span>

      <span
        style={{
          display: 'inline-block',
          width: w,
          transition: 'width 480ms cubic-bezier(.21,.6,.35,1)',
          verticalAlign: 'baseline',
          position: 'relative'
        }}>
        
        {words.map((wd, idx) =>
        <span
          key={idx}
          aria-hidden={idx !== i}
          style={{
            position: idx === i ? 'relative' : 'absolute',
            top: 0,
            left: 0,
            whiteSpace: 'nowrap',
            opacity: idx === i ? 1 : 0,
            transform: idx === i ? 'translateY(0)' : 'translateY(-14px)',
            filter: idx === i ? 'blur(0)' : 'blur(8px)',
            transition: 'opacity 460ms cubic-bezier(.21,.6,.35,1), transform 460ms cubic-bezier(.21,.6,.35,1), filter 460ms',
            color: '#5096FE',
            fontWeight: 700
          }}>
          
            {wd}
          </span>
        )}
      </span>
    </span>);

}

/* ───────── Container-scroll tilting card ───────── */
function useContainerScroll(ref) {
  const [tilt, setTilt] = useState(1); // 0..1 → 1 = tilted, 0 = flat
  useEffect(() => {
    const onScroll = () => {
      const el = ref.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight;
      // 1 when top of section is at top of viewport, 0 when its bottom is at top
      const total = r.height + vh * 0.4;
      const passed = Math.max(0, -r.top + vh * 0.4);
      const p = Math.min(1, Math.max(0, passed / total));
      // We want: top of viewport on landing = tilted, after scrolling = flat
      setTilt(Math.max(0, 1 - p * 2.2));
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [ref]);
  return tilt;
}

/* ───────── Interactive contract preview ───────── */
function ContractPreview() {
  const [active, setActive] = useState(null); // clause id
  const [pinned, setPinned] = useState(null);

  const shown = pinned || active;
  const clause = shown ? CLAUSES.find((c) => c.id === shown) : null;

  return (
    <div className="grid md:grid-cols-5 gap-0 h-full bg-white rounded-2xl overflow-hidden">
      {/* Document side */}
      <div className="md:col-span-3 border-r border-ss-grey300 flex flex-col min-h-0">
        <div className="flex items-center justify-between px-5 py-3 border-b border-ss-grey300 bg-ss-grey100/70">
          <div className="flex items-center gap-2 font-mono text-[11px] text-ss-grey700 uppercase tracking-wider">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#5096FE" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
              <polyline points="14 2 14 8 20 8" />
            </svg>
            Subcontract_Proplex Construction_V.1.pdf
          </div>
        </div>

        <div className="mock-scroll overflow-y-auto px-5 py-5 text-[13px] text-ss-grey900 leading-relaxed flex-1" style={{ maxHeight: '420px' }}>
          {CLAUSES.map((c) => {
            const isActive = shown === c.id;
            const lvl = LEVEL_STYLES[c.flag.level];
            return (
              <div
                key={c.id}
                onMouseEnter={() => setActive(c.id)}
                onMouseLeave={() => setActive(null)}
                onClick={() => setPinned(pinned === c.id ? null : c.id)}
                style={{
                  cursor: 'pointer',
                  padding: '10px 12px',
                  margin: '6px -12px',
                  borderRadius: 8,
                  background: isActive ? lvl.bg : 'transparent',
                  borderLeft: `3px solid ${isActive ? lvl.accent : 'transparent'}`,
                  transition: 'background 180ms, border-color 180ms'
                }}>
                
                <div className="flex items-center gap-2 mb-1.5">
                  <span className="font-mono text-[11px] font-bold" style={{ color: '#1f5fc4' }}>CL {c.n}</span>
                  <span className="text-[11px] uppercase tracking-wider font-semibold text-ss-grey500">{c.title}</span>
                  {isActive &&
                  <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: lvl.text }}>
                      <span style={{ width: 6, height: 6, borderRadius: '50%', background: lvl.dot }} />
                      Flagged
                    </span>
                  }
                </div>
                <p style={{ color: '#525252', fontSize: 13 }}>{c.text}</p>
              </div>);

          })}
          <p className="font-mono text-[10px] text-ss-grey400 mt-2 italic">· hover or click any clause to see SubSync's review ·</p>
        </div>
      </div>

      {/* Flag panel */}
      <div className="md:col-span-2 bg-ss-grey100/40 flex flex-col min-h-0">
        <div className="px-5 py-3 border-b border-ss-grey300 bg-white">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 font-mono text-[11px] text-ss-grey700 uppercase tracking-wider">
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#69c765', boxShadow: '0 0 0 4px rgba(105,199,101,0.18)' }} />
              SubSync · live review
            </div>
            <span className="font-mono text-[10px] text-ss-grey500">3m 12s</span>
          </div>
        </div>

        <div className="p-5 flex-1 overflow-y-auto" style={{ maxHeight: '420px' }}>
          {!clause &&
          <div className="text-center py-10">
              <div className="mx-auto w-12 h-12 rounded-full bg-ss-blue50 flex items-center justify-center mb-4">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#5096FE" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="11" cy="11" r="7" />
                  <line x1="21" y1="21" x2="16.65" y2="16.65" />
                </svg>
              </div>
              <p className="text-[13px] text-ss-grey700 font-medium">Hover a clause →</p>
              <p className="text-[12px] text-ss-grey500 mt-1">See the risk flag, plain-English explanation, and what to push back on.</p>
              <div className="mt-6 grid grid-cols-3 gap-2 text-[10px] font-bold tracking-wider uppercase">
                <div className="rounded p-2" style={{ background: '#ffe7e1', color: '#8a1505' }}>3 High</div>
                <div className="rounded p-2" style={{ background: '#fef5d8', color: '#6b4d00' }}>6 Medium</div>
                <div className="rounded p-2" style={{ background: '#e3f5e1', color: '#1a5a18' }}>5 OK</div>
              </div>
            </div>
          }
          {clause &&
          <FlagDetail clause={clause} />
          }
        </div>
      </div>
    </div>);

}

function FlagDetail({ clause }) {
  const lvl = LEVEL_STYLES[clause.flag.level];
  // animate in
  const [shown, setShown] = useState(false);
  useEffect(() => {
    setShown(false);
    const id = requestAnimationFrame(() => setShown(true));
    return () => cancelAnimationFrame(id);
  }, [clause.id]);

  return (
    <div
      key={clause.id}
      style={{
        opacity: shown ? 1 : 0,
        transform: shown ? 'translateY(0)' : 'translateY(6px)',
        transition: 'opacity 260ms ease, transform 260ms cubic-bezier(.21,.6,.35,1)'
      }}>
      
      <div className="flex items-center gap-2 mb-3">
        <span
          className="flag-chip"
          style={{ background: lvl.bg, color: lvl.text }}>
          
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: lvl.dot }} />
          {clause.flag.label}
        </span>
        <span className="font-mono text-[11px] text-ss-grey500">CL {clause.n}</span>
      </div>
      <h4 className="text-[15px] font-bold text-ss-ink leading-snug">{clause.flag.heading}</h4>
      <p className="text-[13px] text-ss-body mt-2 leading-relaxed">{clause.flag.detail}</p>

      <div className="mt-4 pt-4 border-t border-ss-grey300">
        <p className="font-mono text-[10px] uppercase tracking-wider text-ss-grey500 mb-2">Suggested ask</p>
        <p className="text-[13px] text-ss-grey900 leading-relaxed">{clause.flag.ask}</p>
      </div>

      <div className="mt-5 flex items-center gap-2">
        <button className="btn-primary !py-1.5 !px-3 text-[12px]">Include</button>
        <button className="btn-ghost !py-1.5 !px-3 text-[12px]">Remove</button>
      </div>
    </div>);

}

/* ───────── Hero composition ───────── */
function Hero() {
  const words = typeof window !== 'undefined' && window.__SS_HEADLINE || HERO_ROTATE;
  const stageRef = useRef(null);
  const tilt = useContainerScroll(stageRef);
  const rotate = tilt * 18; // 0..18deg
  const scale = 0.96 + (1 - tilt) * 0.04;

  // ambient spotlight
  const [mp, setMp] = useState({ x: 50, y: 40 });
  const onMove = useCallback((e) => {
    const r = e.currentTarget.getBoundingClientRect();
    setMp({ x: (e.clientX - r.left) / r.width * 100, y: (e.clientY - r.top) / r.height * 100 });
  }, []);

  return (
    <div
      ref={stageRef}
      onMouseMove={onMove}
      className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-16 md:pt-24 pb-20 md:pb-28"
      style={{ position: 'relative', width: "1600px" }}>
      
      {/* ambient spotlight */}
      <div
        aria-hidden="true"
        style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: `radial-gradient(600px circle at ${mp.x}% ${mp.y}%, rgba(0,140,221,0.10), transparent 60%)`,
          transition: 'background 200ms'
        }} />
      

      <div className="relative max-w-5xl">
        <div className="inline-flex items-center gap-2 bg-white border border-ss-grey300 px-3.5 py-1.5 rounded-full mb-7 shadow-ss" style={{ animation: 'heroFadeIn .6s .05s both', margin: '100px 0px 28px' }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#5096FE', boxShadow: '0 0 0 3px rgba(0,140,221,0.18)' }} />
          <span className="text-[12px] font-semibold tracking-wide text-ss-grey900">AI Commercial Reviews for Australian Subcontractors</span>
        </div>

        <h1 className="h-display text-ss-ink" style={{ animation: 'heroFadeIn .7s .15s both' }}>
          <span>Subcontracts</span>
          <br />
          <AnimatedTextCycle words={words} />
        </h1>

        <p className="lede mt-6 max-w-2xl" style={{ animation: 'heroFadeIn .7s .3s both' }}>
          Upload your subcontract and get a plain-English commercial risk review in under <strong className="text-ss-ink">5 minutes</strong>. Built for Australian subcontractors.
        </p>

        <div className="mt-9 flex flex-col sm:flex-row items-start sm:items-center gap-4" style={{ animation: 'heroFadeIn .7s .45s both' }}>
          <a href="#free-reviewer" className="liquid-cta magnet">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
              <polyline points="17 8 12 3 7 8" />
              <line x1="12" y1="3" x2="12" y2="15" />
            </svg>
            Upload a contract
          </a>
          <button type="button" onClick={() => window.__openVideo && window.__openVideo()} className="btn-ghost">
            See how it works
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="6 4 20 12 6 20 6 4" /></svg>
          </button>
        </div>

        <div className="mt-6 flex flex-wrap items-center gap-x-5 gap-y-2 text-[12px] text-ss-grey500" style={{ animation: 'heroFadeIn .8s .55s both', margin: '24px 0px 300px' }}>
          <span className="inline-flex items-center gap-1.5"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg> 5-min review</span>
          <span className="inline-flex items-center gap-1.5"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg> No credit card</span>
          <span className="inline-flex items-center gap-1.5"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg> Built in Melbourne</span>
        </div>
      </div>

      {/* Container-scroll card */}
      <div
        className="mt-14 md:mt-20 mx-auto"
        style={{
          maxWidth: 1080,
          perspective: '1400px'
        }}>
        
        <div
          style={{
            transform: `rotateX(${rotate}deg) scale(${scale})`,
            transformOrigin: 'center top',
            transition: 'transform 80ms linear',
            willChange: 'transform',
            borderRadius: 24,
            padding: 12,
            background: 'linear-gradient(180deg, #7a7d83, #5e6168)',
            boxShadow: '0 30px 80px rgba(15,15,15,0.22), 0 8px 20px rgba(15,15,15,0.10), 0 0 0 1px rgba(255,255,255,0.10) inset'
          }}>
          
          {/* faux browser chrome */}
          <div className="flex items-center gap-1.5 px-3 pt-1.5 pb-3">
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#ff5f57' }} />
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#febc2e' }} />
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#28c840' }} />
            <span className="ml-4 font-mono text-[10px] text-white/50 truncate" style={{ color: "rgb(0, 0, 0)" }}>app.subsync.com.au / review / sub-12a</span>
          </div>
          <ContractPreview />
        </div>
      </div>

      <style>{`
        @keyframes heroFadeIn {
          from { opacity: 0; transform: translateY(14px); }
          to   { opacity: 1; transform: none; }
        }
      `}</style>
    </div>);

}

Object.assign(window, { Hero });