/* Shared layout components, mock UIs, and constants for M-Dash branding site */
const { useState, useEffect, useRef } = React;

const NAV_ITEMS = [
  { href: 'index.html', label: 'Home' },
  { href: 'features.html', label: 'Features' },
  { href: 'blog.html', label: 'Blog' },
  { href: 'about.html', label: 'About' },
];

function Brand({ size = 'md' }) {
  const px = size === 'lg' ? 36 : 28;
  const ws = size === 'lg' ? 22 : 17;
  return (
    <a href="index.html" className="brand" style={{ fontSize: ws, gap: 10 }}>
      {window.MDashLogo ? <window.MDashLogo size={px} /> : <span className="brand-mark" style={{ width: px, height: px }}><span /></span>}
      <span>M<span style={{ color: 'var(--accent-active)' }}>-</span>Dash</span>
    </a>
  );
}

function Nav({ active }) {
  return (
    <header className="nav">
      <div className="container nav-inner">
        <Brand />
        <nav className="nav-links">
          {NAV_ITEMS.map(n => (
            <a key={n.href} href={n.href} className={`nav-link ${active === n.href ? 'active' : ''}`}>{n.label}</a>
          ))}
        </nav>
        <div className="nav-spacer" />
        <div className="nav-cta">
          <a href="https://github.com/karuppan-the-pentester/mdash-web" className="btn btn-ghost btn-sm">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.3 3.44 9.8 8.21 11.39.6.11.82-.26.82-.58v-2.04c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.09-.74.08-.73.08-.73 1.21.08 1.85 1.24 1.85 1.24 1.07 1.84 2.81 1.31 3.5 1 .11-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.12-3.18 0 0 1.01-.32 3.3 1.23.96-.27 1.98-.4 3-.41 1.02.01 2.04.14 3 .41 2.29-1.55 3.3-1.23 3.3-1.23.66 1.66.25 2.88.12 3.18.77.84 1.24 1.91 1.24 3.22 0 4.61-2.81 5.62-5.48 5.92.43.37.81 1.1.81 2.22v3.29c0 .32.22.69.83.58A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"/></svg>
            GitHub
          </a>
          <a href="#waitlist" className="btn btn-primary btn-sm">Join waitlist</a>
        </div>
      </div>
    </header>
  );
}

function BetaPill({ children = 'Beta — not launched yet' }) {
  return (
    <span className="beta-pill">
      <span className="dot" />
      {children}
    </span>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Brand />
            <p style={{ marginTop: 14, color: 'var(--text-2)', fontSize: 14, maxWidth: 280 }}>
              n8n-style flows + Appsmith-style dashboards, in one open-source app. Automate. Visualize.
            </p>
            <div style={{ marginTop: 16 }}><BetaPill>In public beta</BetaPill></div>
          </div>
          <div>
            <h4>Product</h4>
            <ul>
              <li><a href="features.html">Features</a></li>
              <li><a href="use-cases.html">Use cases</a></li>
              <li><a href="plugins.html">Plugins</a></li>
              <li><a href="pricing.html">Pricing</a></li>
            </ul>
          </div>
          <div>
            <h4>Resources</h4>
            <ul>
              <li><a href="docs.html">Docs</a></li>
              <li><a href="blog.html">Blog</a></li>
              <li><a href="blog.html">Changelog</a></li>
              <li><a href="https://github.com/karuppan-the-pentester/mdash-web">GitHub</a></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><a href="about.html">About</a></li>
              <li><a href="contact.html">Contact</a></li>
              <li><a href="contact.html">Community</a></li>
            </ul>
          </div>
          <div>
            <h4>Legal</h4>
            <ul>
              <li><a href="#">License (Apache 2.0)</a></li>
              <li><a href="#">Privacy</a></li>
              <li><a href="#">Terms</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 M-Dash. Open-source under Apache 2.0.</span>
          <div className="links">
            <a href="#">GitHub</a>
            <a href="#">Discord</a>
            <a href="#">Twitter / X</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ───────── Waitlist form ───────── */
function Waitlist({ compact = false }) {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState('idle');
  function submit(e) {
    e.preventDefault();
    if (!email.includes('@')) return;
    setStatus('ok');
    setTimeout(() => setStatus('idle'), 4000);
    setEmail('');
  }
  return (
    <form onSubmit={submit} id="waitlist" style={{
      display: 'flex',
      gap: 8,
      maxWidth: compact ? 420 : 480,
      width: '100%',
      background: 'white',
      padding: 6,
      borderRadius: 'var(--r-lg)',
      border: '1px solid var(--border)',
      boxShadow: 'var(--shadow-sm)',
    }}>
      <input
        type="email"
        value={email}
        onChange={e => setEmail(e.target.value)}
        placeholder="you@company.com"
        style={{
          flex: 1,
          border: 'none',
          outline: 'none',
          padding: '0 14px',
          fontSize: 15,
          fontFamily: 'inherit',
          color: 'var(--text)',
          background: 'transparent',
        }}
      />
      <button type="submit" className="btn btn-primary" style={{ height: 38 }}>
        {status === 'ok' ? '✓ You\'re on the list' : 'Join waitlist'}
      </button>
    </form>
  );
}

/* ───────── Logo strip ───────── */
function LogoStrip() {
  return (
    <div className="logo-strip">
      <div className="logo-item">Lattice</div>
      <div className="logo-item serif">Mercer&amp;Co</div>
      <div className="logo-item mono">/finflow</div>
      <div className="logo-item" style={{ letterSpacing: '0.4em' }}>NORTH</div>
      <div className="logo-item">◆ Pentaprism</div>
      <div className="logo-item serif">Vellum</div>
    </div>
  );
}

/* ============================================================
   MOCK UI — Flow canvas (n8n / XYFlow style)
   ============================================================ */
function FlowMock({ small = false }) {
  return (
    <div className="mock-window" style={{ width: '100%', height: small ? 320 : 380 }}>
      <div className="mock-titlebar">
        <div className="dots"><span /><span /><span /></div>
        <div className="title">Flow — NSE Daily Scrape</div>
      </div>
      <div style={{
        position: 'relative',
        height: 'calc(100% - 32px)',
        background: 'var(--bg-app)',
        backgroundImage: 'radial-gradient(circle, #BAE6FD 1px, transparent 1px)',
        backgroundSize: '20px 20px',
        overflow: 'hidden',
      }}>
        <svg viewBox="0 0 600 320" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          <defs>
            <marker id="arrow-flow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto">
              <path d="M 0 0 L 10 5 L 0 10 z" fill="#0EA5E9" />
            </marker>
          </defs>
          <path className="flow-edge-animated" d="M 130 80 C 180 80, 180 165, 230 165" stroke="#0EA5E9" strokeWidth="2" fill="none" markerEnd="url(#arrow-flow)" />
          <path className="flow-edge-animated" d="M 130 230 C 180 230, 180 165, 230 165" stroke="#0EA5E9" strokeWidth="2" fill="none" markerEnd="url(#arrow-flow)" />
          <path className="flow-edge-animated" d="M 360 165 C 410 165, 410 80, 460 80" stroke="#0EA5E9" strokeWidth="2" fill="none" markerEnd="url(#arrow-flow)" />
          <path className="flow-edge-animated" d="M 360 165 C 410 165, 410 245, 460 245" stroke="#0EA5E9" strokeWidth="2" fill="none" markerEnd="url(#arrow-flow)" />
        </svg>

        <FlowNode x={20} y={50} icon="🌐" title="HTTP Request" subtitle="GET nseindia.com/quote" color="#38BDF8" />
        <FlowNode x={20} y={200} icon="⏱" title="Schedule" subtitle="Every 5 min · 9–4 IST" color="#A78BFA" />
        <FlowNode x={230} y={135} icon="⚙" title="Transform" subtitle="parse JSON · pick(open,close)" color="#0EA5E9" active />
        <FlowNode x={460} y={50} icon="📊" title="Push to Dashboard" subtitle="dashboard: NIFTY-50" color="#059669" />
        <FlowNode x={460} y={215} icon="🗄" title="Postgres Insert" subtitle="table: ohlc_5min" color="#F59E0B" />
      </div>
    </div>
  );
}

function FlowNode({ x, y, icon, title, subtitle, color, active }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width: 130,
      background: 'white',
      border: `1.5px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
      borderRadius: 10,
      boxShadow: active ? '0 0 0 3px rgba(14,165,233,0.18), var(--shadow-sm)' : 'var(--shadow-sm)',
      padding: '8px 10px',
      fontSize: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
        <span style={{
          width: 18, height: 18, borderRadius: 4,
          background: color + '22', color,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 11,
        }}>{icon}</span>
        <span style={{ fontWeight: 600, color: 'var(--text)', fontSize: 11.5 }}>{title}</span>
      </div>
      <div style={{ color: 'var(--text-3)', fontSize: 10.5, fontFamily: 'var(--mono)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {subtitle}
      </div>
      <span style={{
        position: 'absolute', left: -5, top: '50%', transform: 'translateY(-50%)',
        width: 10, height: 10, borderRadius: '50%', background: 'white', border: '2px solid var(--accent)',
      }} />
      <span style={{
        position: 'absolute', right: -5, top: '50%', transform: 'translateY(-50%)',
        width: 10, height: 10, borderRadius: '50%', background: 'var(--accent)', border: '2px solid white',
      }} />
    </div>
  );
}

/* ============================================================
   MOCK UI — Dashboard (Appsmith / react-grid-layout style)
   ============================================================ */
function DashboardMock({ small = false }) {
  return (
    <div className="mock-window" style={{ width: '100%', height: small ? 320 : 380 }}>
      <div className="mock-titlebar">
        <div className="dots"><span /><span /><span /></div>
        <div className="title">Dashboard — NIFTY-50 Live</div>
      </div>
      <div style={{
        position: 'relative',
        height: 'calc(100% - 32px)',
        background: 'var(--bg-app)',
        backgroundImage: 'radial-gradient(circle, #BAE6FD 1.2px, transparent 1.2px)',
        backgroundSize: '18px 18px',
        backgroundPosition: '4px 4px',
        padding: 12,
        display: 'grid',
        gridTemplateColumns: '1fr 1fr 1fr',
        gridTemplateRows: 'auto 1fr',
        gap: 10,
      }}>
        <StatWidget label="NIFTY 50" value="24,812.35" delta="+1.24%" up />
        <StatWidget label="Volume" value="312.4M" delta="+8.1%" up />
        <StatWidget label="Volatility" value="14.2" delta="-2.3" />
        <ChartWidget />
        <TableWidget />
      </div>
    </div>
  );
}

function StatWidget({ label, value, delta, up }) {
  const [tickKey, setTickKey] = React.useState(0);
  const [pulse, setPulse] = React.useState(false);
  React.useEffect(() => {
    const offset = (label.charCodeAt(0) % 5) * 700;
    const id = setInterval(() => {
      setPulse(true);
      setTickKey(k => k + 1);
      setTimeout(() => setPulse(false), 600);
    }, 4200 + offset);
    return () => clearInterval(id);
  }, [label]);
  return (
    <div style={{
      background: 'white',
      border: '1px solid var(--border)',
      borderRadius: 8,
      padding: '10px 12px',
      boxShadow: pulse ? '0 0 0 2px rgba(14,165,233,0.20), var(--shadow-xs)' : 'var(--shadow-xs)',
      transition: 'box-shadow 250ms ease',
    }}>
      <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 500, marginBottom: 4 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span key={tickKey} className="tick" style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.4px' }}>{value}</span>
        <span style={{
          fontSize: 11, fontWeight: 600, fontFamily: 'var(--mono)',
          color: up ? 'var(--success)' : 'var(--error)',
        }}>{delta}</span>
      </div>
    </div>
  );
}

function ChartWidget() {
  return (
    <div style={{
      gridColumn: '1 / 3',
      background: 'white',
      border: '1px solid var(--border)',
      borderRadius: 8,
      padding: '10px 12px',
      boxShadow: 'var(--shadow-xs)',
      position: 'relative',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
        <span style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 500 }}>Price · 1D</span>
        <span style={{ fontSize: 10, color: 'var(--text-4)', fontFamily: 'var(--mono)' }}>line</span>
      </div>
      <svg viewBox="0 0 320 100" style={{ width: '100%', height: 'calc(100% - 22px)' }}>
        <defs>
          <linearGradient id="cg" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#0EA5E9" stopOpacity="0.25" />
            <stop offset="100%" stopColor="#0EA5E9" stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d="M0,72 C30,68 50,40 80,42 C110,44 130,80 160,76 C190,72 210,30 240,28 C270,26 290,52 320,40 L320,100 L0,100 Z" fill="url(#cg)" />
        <path d="M0,72 C30,68 50,40 80,42 C110,44 130,80 160,76 C190,72 210,30 240,28 C270,26 290,52 320,40" fill="none" stroke="#0EA5E9" strokeWidth="2" />
        <circle cx="240" cy="28" r="3" fill="#0EA5E9" />
      </svg>
    </div>
  );
}

function TableWidget() {
  const rows = [
    ['RELIANCE', '2,914', '+1.4%', true],
    ['TCS', '4,012', '+0.8%', true],
    ['HDFC BANK', '1,684', '-0.3%', false],
    ['INFY', '1,821', '+2.1%', true],
  ];
  return (
    <div style={{
      background: 'white',
      border: '1px solid var(--border)',
      borderRadius: 8,
      padding: '8px 10px',
      boxShadow: 'var(--shadow-xs)',
      overflow: 'hidden',
    }}>
      <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 500, marginBottom: 6 }}>Top movers</div>
      <table style={{ width: '100%', fontSize: 10.5, borderCollapse: 'collapse' }}>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} style={{ borderTop: i ? '1px solid var(--border)' : 'none' }}>
              <td style={{ padding: '4px 0', fontWeight: 500 }}>{r[0]}</td>
              <td style={{ padding: '4px 0', fontFamily: 'var(--mono)', textAlign: 'right' }}>{r[1]}</td>
              <td style={{
                padding: '4px 0', fontFamily: 'var(--mono)', textAlign: 'right',
                color: r[3] ? 'var(--success)' : 'var(--error)', fontWeight: 600,
              }}>{r[2]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ============================================================
   Animated split: flow → dashboard (with arrow showing pipeline)
   ============================================================ */
function PipelineHero() {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '1fr auto 1fr',
      alignItems: 'center',
      gap: 20,
      width: '100%',
    }}>
      <FlowMock small />
      <PipelineArrow />
      <DashboardMock small />
    </div>
  );
}

function PipelineArrow() {
  return (
    <div style={{
      position: 'relative',
      width: 64,
      height: 200,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    }}>
      <svg width="64" height="80" viewBox="0 0 64 80">
        <defs>
          <linearGradient id="arrow-grad" x1="0" x2="1">
            <stop offset="0%" stopColor="#0EA5E9" stopOpacity="0" />
            <stop offset="50%" stopColor="#0EA5E9" />
            <stop offset="100%" stopColor="#0EA5E9" />
          </linearGradient>
        </defs>
        <path d="M 0 40 L 50 40" stroke="url(#arrow-grad)" strokeWidth="3" strokeDasharray="4 4" fill="none">
          <animate attributeName="stroke-dashoffset" from="0" to="-16" dur="1s" repeatCount="indefinite" />
        </path>
        <path d="M 44 32 L 60 40 L 44 48 Z" fill="#0EA5E9" />
      </svg>
      <div style={{
        position: 'absolute',
        top: 'calc(50% + 28px)',
        fontFamily: 'var(--mono)',
        fontSize: 10,
        color: 'var(--accent-active)',
        background: 'var(--accent-50)',
        padding: '2px 8px',
        borderRadius: 999,
        border: '1px solid var(--accent-200)',
        whiteSpace: 'nowrap',
      }}>
        live
      </div>
    </div>
  );
}

/* Mount helper — every page calls this at the bottom */
function mountPage(PageComponent) {
  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(<PageComponent />);
}

Object.assign(window, {
  Brand, Nav, Footer, BetaPill, Waitlist, LogoStrip,
  FlowMock, DashboardMock, PipelineHero, FlowNode,
  StatWidget, ChartWidget, TableWidget,
  NAV_ITEMS, mountPage,
});
