const { useState, useEffect, useRef } = React;

function Logo({ size = 'md' }) {
  // Exact lockup from vyovam.com — tall pill V mark + heavy VYOVAM wordmark, all white on navy
  return (
    <div className={`logo logo-${size}`}>
      <svg className="logo-mark-svg" viewBox="0 0 234 200" aria-hidden="true">
        <rect x="58" y="15" width="118" height="168" rx="59" ry="59"
          fill="none" stroke="currentColor" strokeWidth="8" />
        <text x="117" y="148" textAnchor="middle"
          fontFamily="Geist, sans-serif" fontSize="108" fontWeight="900" fill="currentColor">V</text>
      </svg>
      <div className="logo-text">
        <span className="logo-word">VYOVAM</span>
        <span className="logo-sub">TECH SERVICES LLC</span>
      </div>
    </div>);

}

/* ------------ Theme toggle: Day / Night / Auto ------------ */
function ThemeToggle() {
  const [mode, setMode] = useState(() => {
    try { return localStorage.getItem('vyovam-theme') || 'auto'; } catch (e) { return 'auto'; }
  });

  useEffect(() => {
    try { localStorage.setItem('vyovam-theme', mode); } catch (e) {}
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const apply = () => {
      const dark = mode === 'dark' || (mode === 'auto' && mq.matches);
      document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
    };
    apply();
    mq.addEventListener('change', apply);
    return () => mq.removeEventListener('change', apply);
  }, [mode]);

  const next = { auto: 'light', light: 'dark', dark: 'auto' };
  const labels = { auto: 'Auto', light: 'Day', dark: 'Night' };
  const icons = {
    light: (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
        <circle cx="12" cy="12" r="4" />
        <path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1" />
      </svg>
    ),
    dark: (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
        <path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z" />
      </svg>
    ),
    auto: (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
        <circle cx="12" cy="12" r="9" />
        <path d="M12 3a9 9 0 0 1 0 18Z" fill="currentColor" stroke="none" />
      </svg>
    )
  };

  return (
    <button className="theme-toggle" onClick={() => setMode(next[mode])}
      title={`Theme: ${labels[mode]} — click to switch`}
      aria-label={`Theme: ${labels[mode]}. Click to switch theme.`}>
      {icons[mode]}
      <span className="tt-label">{labels[mode]}</span>
    </button>
  );
}

function Nav({ page, setPage }) {
  const [open, setOpen] = useState(false);
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'infrastructure', label: 'Algo Trading' },
    { id: 'ecommerce', label: 'E-Commerce', soon: true },
    { id: 'fluentme', label: 'FluentMe' },
    { id: 'contact', label: 'Contact' }
  ];
  const go = (id) => (e) => { e.preventDefault(); setPage(id); setOpen(false); };
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a href="#/home" onClick={go('home')}>
          <Logo />
        </a>
        <div className="nav-right">
          <div className="nav-links">
            {links.map((l, i) =>
              <a key={i} href={`#/${l.id}`}
                className={`nav-link ${page === l.id ? 'active' : ''}`}
                onClick={go(l.id)}>
                {l.label}
                {l.soon && <sup className="nav-soon">soon</sup>}
              </a>
            )}
          </div>
          <ThemeToggle />
          <button className="nav-burger" onClick={() => setOpen(!open)}
            aria-label={open ? 'Close menu' : 'Open menu'} aria-expanded={open}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
              {open
                ? <path d="M5 5l14 14M19 5 5 19" />
                : <path d="M3 6h18M3 12h18M3 18h18" />}
            </svg>
          </button>
        </div>
      </div>
      {open && (
        <div className="nav-mobile">
          {links.map((l, i) =>
            <a key={i} href={`#/${l.id}`}
              className={`nav-mobile-link ${page === l.id ? 'active' : ''}`}
              onClick={go(l.id)}>
              {l.label}
              {l.soon && <sup className="nav-soon">soon</sup>}
            </a>
          )}
        </div>
      )}
    </nav>);
}

/* ------------ Live ticker bar (custom scrolling marquee) ------------
   Sensex + Nifty (Algomind) scroll together with the global markets
   (Yahoo Finance) via one server-side proxy. Fully theme-aware — no
   third-party widget, so no day/night colour desync. */
function Ticker() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    let alive = true;
    const load = async () => {
      try {
        const r = await fetch('ticker-data.php', { cache: 'no-store' });
        if (!r.ok) return;
        const j = await r.json();
        if (alive && j && Array.isArray(j.items) && j.items.length) setItems(j.items);
      } catch (e) { /* keep last good data */ }
    };
    load();
    const id = setInterval(load, 30000);
    return () => { alive = false; clearInterval(id); };
  }, []);

  const fmt = (p, dp) => Number(p).toLocaleString('en-US', { minimumFractionDigits: dp, maximumFractionDigits: dp });
  const renderItem = (it, key) => {
    const pct = Number(it.changePct) || 0;
    const cls = pct > 0 ? 'up' : pct < 0 ? 'down' : 'flat';
    const arrow = pct > 0 ? '▲' : pct < 0 ? '▼' : '·';
    return (
      <span className="mkt-item" key={key}>
        <span className="mkt-name">{it.name}</span>
        <span className="mkt-price">{fmt(it.price, it.dp || 2)}</span>
        <span className={`mkt-chg ${cls}`}>{arrow} {Math.abs(pct).toFixed(2)}%</span>
        <span className="mkt-sep">·</span>
      </span>
    );
  };

  const loop = [...items, ...items];
  const dur = Math.max(28, items.length * 4.5); // seconds — consistent scroll speed

  return (
    <div className="ticker" aria-label="Live market ticker">
      <div className="wrap ticker-wrap">
        <span className="ticker-note">Live</span>
        <div className="ticker-clip">
          {items.length ? (
            <div className="mkt-track" style={{ animationDuration: `${dur}s` }}>
              {loop.map((it, i) => renderItem(it, i))}
            </div>
          ) : (
            <div className="mkt-loading">Loading live market data…</div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ------------ Sparkline ------------ */
function Sparkline({ seed = 1, up = true }) {
  const points = React.useMemo(() => {
    const n = 30;
    const arr = [];
    let v = 50;
    let rng = seed;
    const rand = () => { rng = (rng * 9301 + 49297) % 233280; return rng / 233280; };
    for (let i = 0; i < n; i++) {
      const drift = up ? 0.6 : -0.4;
      v += (rand() - 0.5) * 6 + drift;
      arr.push(Math.max(10, Math.min(90, v)));
    }
    return arr;
  }, [seed, up]);
  const w = 200, h = 48;
  const path = points.map((p, i) => {
    const x = (i / (points.length - 1)) * w;
    const y = h - (p / 100) * h;
    return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(' ');
  const area = `${path} L ${w} ${h} L 0 ${h} Z`;
  const color = up ? '#4ade80' : '#f87171';
  const gradId = `sparkG-${seed}`;
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id={gradId} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.22" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${gradId})`} />
      <path d={path} fill="none" stroke={color} strokeWidth="1.4" />
    </svg>
  );
}

/* ------------ Star rating ------------ */
function Stars({ count = 5 }) {
  return (
    <div className="stars" aria-label={`${count} of 5 stars`}>
      {Array.from({ length: count }).map((_, i) => (
        <svg key={i} viewBox="0 0 20 20" fill="currentColor">
          <path d="M10 1.5l2.6 5.3 5.9.9-4.2 4.1 1 5.8L10 14.9l-5.3 2.7 1-5.8-4.2-4.1 5.9-.9z" />
        </svg>
      ))}
    </div>
  );
}

function Footer({ setPage }) {
  return (
    <footer>
      <div className="wrap">
        <div className="footer-grid" style={{ gridTemplateColumns: '1.6fr 1fr 1fr 1.2fr' }}>
          <div className="footer-brand">
            <Logo />
            <p>Vyovam Tech Services LLC builds algorithmic trading infrastructure, operates full-service e-commerce for performance-focused brands, and creates consumer AI applications like FluentMe — all on one real-time engineering core.</p>
          </div>
          <div className="footer-col">
            <h5>Navigate</h5>
            <ul>
              <li><a href="#/home" onClick={(e) => { e.preventDefault(); setPage('home'); }}>Home</a></li>
              <li><a href="#/infrastructure" onClick={(e) => { e.preventDefault(); setPage('infrastructure'); }}>Algo Trading</a></li>
              <li><a href="#/ecommerce" onClick={(e) => { e.preventDefault(); setPage('ecommerce'); }}>E-Commerce</a></li>
              <li><a href="#/contact" onClick={(e) => { e.preventDefault(); setPage('contact'); }}>Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Products</h5>
            <ul>
              <li><a href="#/fluentme" onClick={(e) => { e.preventDefault(); setPage('fluentme'); }}>FluentMe</a></li>
              <li><a href="https://fluentme.ai" target="_blank" rel="noopener">fluentme.ai ↗</a></li>
              <li><a href="#/infrastructure" onClick={(e) => { e.preventDefault(); setPage('infrastructure'); }}>Algo Trading Platform</a></li>
              <li><a href="#/ecommerce" onClick={(e) => { e.preventDefault(); setPage('ecommerce'); }}>E-Commerce <span style={{ fontSize: 10, opacity: 0.7 }}>(soon)</span></a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <ul>
              <li><a href="#/about" onClick={(e) => { e.preventDefault(); setPage('about'); }}>About Vyovam</a></li>
              <li><a href="mailto:care@vyovam.com">care@vyovam.com</a></li>
              <li style={{ color: 'var(--text-secondary)', fontSize: 13, lineHeight: 1.5 }}>1788 Glenstone Court<br/>San Jose, CA 95121, USA</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Vyovam Tech Services LLC · All rights reserved</span>
        </div>
      </div>
    </footer>);

}

function HeroChart() {
  // generate a synthetic upward chart with noise
  const points = React.useMemo(() => {
    const n = 80;
    const arr = [];
    let v = 30;
    for (let i = 0; i < n; i++) {
      v += Math.sin(i * 0.4) * 1.2 + i / n * 1.4 + (Math.random() - 0.45) * 2.4;
      arr.push(Math.max(8, Math.min(92, v)));
    }
    return arr;
  }, []);

  const w = 400,h = 240;
  const path = points.map((p, i) => {
    const x = i / (points.length - 1) * w;
    const y = h - p / 100 * h;
    return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(' ');
  const area = `${path} L ${w} ${h} L 0 ${h} Z`;

  // Drawing animation
  const [drawn, setDrawn] = useState(false);
  useEffect(() => {const t = setTimeout(() => setDrawn(true), 100);return () => clearTimeout(t);}, []);

  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id="areaG" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#c9a961" stopOpacity="0.28" />
          <stop offset="100%" stopColor="#c9a961" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#areaG)" style={{ opacity: drawn ? 1 : 0, transition: 'opacity 1.4s ease 0.6s' }} />
      <path d={path} fill="none" stroke="#c9a961" strokeWidth="1.5"
      strokeDasharray="2000"
      strokeDashoffset={drawn ? 0 : 2000}
      style={{ transition: 'stroke-dashoffset 2s ease' }} />
      {/* marker dots */}
      {[20, 40, 60].map((i) => {
        const p = points[i];
        const x = i / (points.length - 1) * w;
        const y = h - p / 100 * h;
        return <circle key={i} cx={x} cy={y} r="2.5" fill="#c9a961" opacity={drawn ? 1 : 0} style={{ transition: `opacity .4s ease ${1.5 + i * 0.05}s` }} />;
      })}
      {/* end marker */}
      <circle cx={w} cy={h - points[points.length - 1] / 100 * h} r="4" fill="#e2c47a" opacity={drawn ? 1 : 0} style={{ transition: 'opacity .4s ease 2s' }}>
        <animate attributeName="r" values="4;7;4" dur="2s" repeatCount="indefinite" />
      </circle>
    </svg>);

}

function Marquee() {
  const items = [
  'Equities', 'Derivatives', 'FX', 'Crypto', 'Amazon Seller Central',
  'Shopify', 'Walmart Marketplace', 'eBay', 'Inventory Sync',
  'Order Automation', 'Backtesting', 'Risk Management'];

  // duplicate so loop is seamless
  const list = [...items, ...items];
  return (
    <div className="hero-marquee">
      <div className="marquee-track">
        {list.map((s, i) =>
        <span key={i}><span className="dot">◆</span> {s}</span>
        )}
      </div>
    </div>);

}

function Reveal({ children, delay = 0 }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setTimeout(() => setShown(true), delay);
        obs.unobserve(el);
      }
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <div ref={ref} className={`reveal ${shown ? 'in' : ''}`}>{children}</div>);

}

Object.assign(window, { Logo, Nav, Footer, HeroChart, Marquee, Reveal, Ticker, Sparkline, Stars });