/* SKOPIA Landing — Hero dashboard mockup */

const Sparkline = ({ values, w = 200, h = 40, stroke = '#4A6FE8', fill = 'rgba(74,111,232,0.12)' }) => {
  const max = Math.max(...values),min = Math.min(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => {
    const x = i / (values.length - 1) * w;
    const y = h - (v - min) / range * (h - 6) - 3;
    return [x, y];
  });
  const d = pts.map((p, i) => i === 0 ? `M ${p[0]} ${p[1]}` : `L ${p[0]} ${p[1]}`).join(' ');
  const area = `${d} L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      <path d={area} fill={fill} />
      <path d={d} fill="none" stroke={stroke} strokeWidth="1.8" strokeLinecap="round" />
    </svg>);

};

/* Gantt-style bars */
const GanttRow = ({ label, start, len, color = 'var(--color-grad-90)', progress = 1, code }) =>
<div style={{ display: 'grid', gridTemplateColumns: '120px 56px 1fr', alignItems: 'center', gap: 12, padding: '7px 0', borderBottom: '1px solid #F1F3FA' }}>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
      <span style={{ fontFamily: 'var(--font-head)', fontSize: 11, fontWeight: 700, color: '#1A1A2E', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
      <span className="mono" style={{ fontSize: 9, color: '#9AA0B0' }}>{code}</span>
    </div>
    <span className="mono" style={{ fontSize: 10, color: '#6B7280' }}>{Math.round(progress * 100)}%</span>
    <div style={{ position: 'relative', height: 12, background: '#F4F6FB', borderRadius: 3 }}>
      <div style={{
      position: 'absolute', left: `${start}%`, width: `${len}%`,
      height: '100%', background: color, borderRadius: 3
    }} />
      <div style={{
      position: 'absolute', left: `${start}%`, width: `${len * progress}%`,
      height: '100%', background: 'rgba(0,0,0,0.18)', borderRadius: 3
    }} />
    </div>
  </div>;


const ScoreRing = ({ value = 90, size = 80 }) => {
  const r = (size - 10) / 2,c = 2 * Math.PI * r;
  const offset = c - value / 100 * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <defs>
          <linearGradient id="ring-grad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#1EC8D4" />
            <stop offset="100%" stopColor="#2A4DCC" />
          </linearGradient>
        </defs>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#EEF1F8" strokeWidth="6" />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="url(#ring-grad)" strokeWidth="6"
        strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round" />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 500, color: '#1A1A2E' }}>{value.toFixed(1)}</span>
        <span style={{ fontFamily: 'var(--font-head)', fontSize: 9, fontWeight: 700, letterSpacing: 1.5, color: '#6B7280' }}>SCORE</span>
      </div>
    </div>);

};

/* S-curve mini chart */
const SCurve = ({ w = 260, h = 110 }) => {
  const planned = [0, 4, 12, 26, 44, 60, 74, 84, 92, 97, 100];
  const actual = [0, 3, 9, 20, 36, 52, 65, 73, 78, null, null];
  const x = (i) => i / 10 * w;
  const y = (v) => h - 12 - v / 100 * (h - 24);
  const lineP = planned.map((v, i) => `${i ? 'L' : 'M'} ${x(i)} ${y(v)}`).join(' ');
  const lineA = actual.filter((v) => v !== null).map((v, i) => `${i ? 'L' : 'M'} ${x(i)} ${y(v)}`).join(' ');
  const areaP = lineP + ` L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      <defs>
        <linearGradient id="sc-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(74,111,232,0.18)" />
          <stop offset="100%" stopColor="rgba(74,111,232,0.02)" />
        </linearGradient>
      </defs>
      {[0, 0.33, 0.66, 1].map((p) =>
      <line key={p} x1="0" x2={w} y1={12 + p * (h - 24)} y2={12 + p * (h - 24)} stroke="#F1F3FA" strokeDasharray="2 3" />
      )}
      <path d={areaP} fill="url(#sc-grad)" />
      <path d={lineP} fill="none" stroke="#4A6FE8" strokeWidth="2" strokeDasharray="4 3" />
      <path d={lineA} fill="none" stroke="#1EC8D4" strokeWidth="2.2" />
      {actual.filter((v) => v !== null).map((v, i) =>
      <circle key={i} cx={x(i)} cy={y(v)} r="2.4" fill="#fff" stroke="#1EC8D4" strokeWidth="1.5" />
      )}
    </svg>);

};

/* The hero dashboard — auto-advancing slideshow of real product screens */
const HeroDashboard = () => {
  const slides = [
  { src: 'assets/hero-command-hub.png', label: 'Command hub' },
  { src: 'assets/hero-upload.png', label: 'Upload & analyse' },
  { src: 'assets/hero-converter.png', label: 'Format converter' },
  { src: 'assets/hero-gantt.png', label: 'Gantt · critical path' },
  { src: 'assets/hero-health.png', label: 'Schedule health · DCMA' },
  { src: 'assets/hero-check-detail.png', label: 'Logic density drill-in' }];


  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [progress, setProgress] = useState(0);
  const SLIDE_MS = 4500;

  // Pause when off-screen
  const wrapperRef = useRef(null);
  const [inView, setInView] = useState(true);
  useEffect(() => {
    const el = wrapperRef.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Auto-advance via RAF — drives a progress bar then steps to next
  useEffect(() => {
    if (paused || !inView) return;
    const start = performance.now() - progress * SLIDE_MS;
    let raf;
    const tick = (now) => {
      const p = Math.min(1, (now - start) / SLIDE_MS);
      setProgress(p);
      if (p >= 1) {
        setIdx((i) => (i + 1) % slides.length);
        setProgress(0);
      } else {
        raf = requestAnimationFrame(tick);
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line
  }, [idx, paused, inView]);

  const goTo = (i) => {setIdx(i);setProgress(0);};
  const prevIdx = (idx - 1 + slides.length) % slides.length;
  const nextIdx = (idx + 1) % slides.length;

  return (
    <div
      ref={wrapperRef}
      style={{ position: 'relative', width: '100%' }}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}>
      
      {/* Floating slide label (top-center) */}
      <div style={{
        position: 'absolute', top: -22, left: '50%', transform: 'translateX(-50%)',
        zIndex: 3,
        display: 'inline-flex', alignItems: 'center', gap: 10,
        padding: '7px 16px', borderRadius: 999,
        background: '#fff', border: '1px solid #E2E6F0',
        boxShadow: '0 12px 30px -8px rgba(42,77,204,0.18)',
        fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 11, letterSpacing: 0.4,
        whiteSpace: 'nowrap'
      }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--color-grad)' }} />
        <span key={'lbl-' + idx} style={{
          background: 'var(--color-grad)',
          WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
          backgroundClip: 'text',
          animation: 'hero-label-in .35s ease both'
        }}>{slides[idx].label}</span>
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 500,
          color: '#9AA0B0', letterSpacing: 0.5
        }}>{String(idx + 1).padStart(2, '0')} / {String(slides.length).padStart(2, '0')}</span>
      </div>

      {/* Background offset peek of the next slide */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0, zIndex: 0,
        transform: 'translate(28px, 28px) scale(0.96)',
        opacity: 0.32, filter: 'blur(2px)',
        borderRadius: 8, overflow: 'hidden',
        border: '1px solid #E2E6F0',
        boxShadow: '0 30px 60px -30px rgba(42,77,204,0.3)',
        transition: 'opacity .4s ease'
      }}>
        <img
          src={slides[nextIdx].src}
          alt=""
          style={{ display: 'block', width: '100%', height: 'auto' }} />
        
      </div>

      {/* Main framed slide stack */}
      <div style={{
        position: 'relative', zIndex: 1,
        background: '#fff',
        borderRadius: 8,
        border: '1px solid #E2E6F0',
        boxShadow: '0 30px 80px -20px rgba(42,77,204,0.28), 0 12px 30px rgba(0,0,0,0.08)',
        overflow: 'hidden'
      }}>
        <GradBar height={3} />

        {/* Stack: all images layered, cross-fade between them */}
        <div style={{ position: 'relative', width: '100%', aspectRatio: '1276 / 600', background: '#0c0d12' }}>
          {slides.map((s, i) =>
          <img
            key={s.src}
            src={s.src}
            alt={`SKOPIA Lens — ${s.label}`}
            loading={i === 0 ? 'eager' : 'lazy'}
            style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%', objectFit: 'cover',
              opacity: i === idx ? 1 : 0,
              transform: i === idx ? 'scale(1.005)' : 'scale(1.02)',
              transition: 'opacity .55s ease, transform 6s ease-out',
              pointerEvents: i === idx ? 'auto' : 'none'
            }} />

          )}
        </div>

        {/* Bottom control strip */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 14,
          padding: '12px 18px',
          borderTop: '1px solid #EFF1F7', background: '#fff'
        }}>
          {/* Prev */}
          <button onClick={() => goTo(prevIdx)} aria-label="Previous" style={ctrlBtn}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 6l-6 6 6 6" /></svg>
          </button>
          {/* Play/pause */}
          <button onClick={() => setPaused((p) => !p)} aria-label={paused ? 'Play' : 'Pause'} style={{
            ...ctrlBtn, background: 'var(--color-grad)', color: '#fff', border: 'none',
            boxShadow: '0 4px 14px rgba(42,77,204,0.30)'
          }}>
            {paused ?
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M7 5l12 7-12 7V5z" /></svg> :
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1" /><rect x="14" y="5" width="4" height="14" rx="1" /></svg>}
          </button>
          {/* Next */}
          <button onClick={() => goTo(nextIdx)} aria-label="Next" style={ctrlBtn}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6" /></svg>
          </button>

          {/* Segmented progress bar — one segment per slide */}
          <div style={{ flex: 1, display: 'flex', gap: 4, marginLeft: 4 }}>
            {slides.map((_, i) => {
              const fill = i < idx ? 1 : i === idx ? progress : 0;
              return (
                <button key={i} onClick={() => goTo(i)} aria-label={`Slide ${i + 1}`} style={{
                  flex: 1, height: 4, padding: 0, border: 'none',
                  background: '#EFF1F7', borderRadius: 999, position: 'relative',
                  cursor: 'pointer', overflow: 'hidden'
                }}>
                  <span style={{
                    position: 'absolute', inset: 0,
                    width: fill * 100 + '%',
                    background: 'var(--color-grad)',
                    transition: i === idx ? 'none' : 'width .2s ease'
                  }}></span>
                </button>);

            })}
          </div>
        </div>
      </div>

      {/* Floating accent label bottom-right */}
      <div style={{
        position: 'absolute', bottom: -16, right: 32, zIndex: 2,
        padding: '8px 14px', borderRadius: 999,
        background: '#1E1E1E', color: '#fff',
        fontFamily: 'var(--font-mono)', fontSize: 11,
        boxShadow: '0 12px 30px -10px rgba(0,0,0,0.3)',
        display: 'inline-flex', alignItems: 'center', gap: 8
      }}>
        <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#16A34A', boxShadow: '0 0 10px #16A34A' }}></span>
        live · skopia.com.au / lens
      </div>

      <style>{`
        @keyframes hero-label-in {
          from { opacity: 0; transform: translateY(-4px); }
          to   { opacity: 1; transform: none; }
        }
      `}</style>
    </div>);

};

const ctrlBtn = {
  width: 30, height: 30, borderRadius: '50%',
  border: '1px solid #E2E6F0', background: '#fff', cursor: 'pointer',
  color: '#1A1A2E',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  flexShrink: 0
};

const AICommentaryCard = () =>
<div style={{
  width: 240,
  background: '#fff',
  border: '1px solid #E2E6F0',
  borderRadius: 6,
  padding: 14,
  boxShadow: '0 18px 50px -12px rgba(42,77,204,0.18)'
}}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
      <div style={{ width: 22, height: 22, borderRadius: 4, background: 'var(--color-grad)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name="spark" size={12} color="#fff" stroke={2} />
      </div>
      <span style={{ fontFamily: 'var(--font-head)', fontSize: 10, fontWeight: 700, letterSpacing: 1.5, color: '#1A1A2E' }}>AI COMMENTARY</span>
    </div>
    <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, lineHeight: 1.55, color: '#1A1A2E' }}>
      Critical path now runs through <span className="mono" style={{ color: '#2A4DCC', fontSize: 10.5 }}>A1040 In-situ Concrete</span>. SPI dropped 0.04 since last update — <strong>2 day slip likely</strong> by milestone M-12.
    </div>
    <div style={{ marginTop: 10, display: 'flex', gap: 4 }}>
      <span style={{ padding: '3px 8px', borderRadius: 999, background: '#FFF5F5', color: '#DC2626', fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 9 }}>HIGH</span>
      <span style={{ padding: '3px 8px', borderRadius: 999, background: '#F1F3FA', color: '#6B7280', fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 9 }}>MILESTONE</span>
    </div>
  </div>;


const EVMCard = () =>
<div style={{
  width: 230,
  background: '#fff',
  border: '1px solid #E2E6F0',
  borderRadius: 6,
  padding: 14,
  boxShadow: '0 18px 50px -12px rgba(42,77,204,0.18)'
}}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
      <span style={{ fontFamily: 'var(--font-head)', fontSize: 10, fontWeight: 700, letterSpacing: 1.5, color: '#9AA0B0' }}>EVM SNAPSHOT</span>
      <span className="mono" style={{ fontSize: 9, color: '#9AA0B0' }}>WK 24</span>
    </div>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 8 }}>
      <div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 500, color: '#1A1A2E' }}>$32.4M</div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 10, color: '#6B7280' }}>Earned value</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="mono" style={{ fontSize: 12, color: '#16A34A' }}>+ 4.2%</div>
        <div style={{ fontSize: 9, color: '#6B7280' }}>vs plan</div>
      </div>
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
      {[
    { k: 'PV', v: '$33.8M' },
    { k: 'AC', v: '$33.4M' },
    { k: 'CV', v: '−$1.0M' },
    { k: 'SV', v: '−$1.4M' }].
    map((r) =>
    <div key={r.k} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 8px', background: '#FAFBFE', borderRadius: 3 }}>
          <span style={{ fontFamily: 'var(--font-head)', fontSize: 9, fontWeight: 700, color: '#9AA0B0', letterSpacing: 1 }}>{r.k}</span>
          <span className="mono" style={{ fontSize: 10, color: '#1A1A2E' }}>{r.v}</span>
        </div>
    )}
    </div>
  </div>;


Object.assign(window, { HeroDashboard, AICommentaryCard, EVMCard, Sparkline, ScoreRing, SCurve });