// SC AccountPro — Login Screen
// Glass-morphism card, animated AI background, focus glow, logo shimmer, dark mode.

const { useState, useEffect, useRef, useMemo } = React;

// ─────────────────────────────────────────────────────────────
// Theme palettes — keyed by accent + mode
// ─────────────────────────────────────────────────────────────
const PALETTES = {
  navy: {
    light: {
      bgFrom: '#0a2358', bgVia: '#0f3179', bgTo: '#1a4fa6',
      cardBg: 'rgba(255,255,255,0.92)', cardBorder: 'rgba(255,255,255,0.6)',
      text: '#0b1f4a', textMuted: '#4b5b7a', textSubtle: '#8693ad',
      inputBg: '#ffffff', inputBorder: '#e3e8f0', inputBorderFocus: '#2563eb',
      btnFrom: '#1d4ed8', btnTo: '#3b82f6', btnGlow: 'rgba(37,99,235,0.45)',
      net: 'rgba(120,170,255,0.35)', netGlow: '#5b9eff',
      gold: '#f4c14a', goldDeep: '#d99820',
      featTint: 'rgba(255,255,255,0.08)', featIcon: '#60a5fa', featText: 'rgba(255,255,255,0.78)',
      pillBg: 'rgba(10,25,60,0.55)', pillBorder: 'rgba(244,193,74,0.35)', pillText: '#ffd97a',
      footerText: 'rgba(255,255,255,0.55)', footerSub: 'rgba(255,255,255,0.4)'
    },
    dark: {
      bgFrom: '#02060f', bgVia: '#050d22', bgTo: '#0a1a3a',
      cardBg: 'rgba(18,28,52,0.78)', cardBorder: 'rgba(120,160,230,0.18)',
      text: '#eaf0ff', textMuted: '#94a3c4', textSubtle: '#5d6c8c',
      inputBg: 'rgba(8,15,32,0.6)', inputBorder: 'rgba(120,160,230,0.18)', inputBorderFocus: '#60a5fa',
      btnFrom: '#1e40af', btnTo: '#3b82f6', btnGlow: 'rgba(96,165,250,0.45)',
      net: 'rgba(120,170,255,0.28)', netGlow: '#4f8eff',
      gold: '#f4c14a', goldDeep: '#d99820',
      featTint: 'rgba(255,255,255,0.04)', featIcon: '#7eb6ff', featText: 'rgba(220,232,255,0.7)',
      pillBg: 'rgba(8,18,42,0.7)', pillBorder: 'rgba(244,193,74,0.3)', pillText: '#ffd97a',
      footerText: 'rgba(220,232,255,0.45)', footerSub: 'rgba(220,232,255,0.32)'
    }
  },
  emerald: {
    light: {
      bgFrom: '#052e2a', bgVia: '#0b4a3f', bgTo: '#11705c',
      cardBg: 'rgba(255,255,255,0.92)', cardBorder: 'rgba(255,255,255,0.6)',
      text: '#04261f', textMuted: '#3a5a52', textSubtle: '#7f9a92',
      inputBg: '#ffffff', inputBorder: '#dfeae5', inputBorderFocus: '#0d9488',
      btnFrom: '#0f766e', btnTo: '#14b8a6', btnGlow: 'rgba(20,184,166,0.45)',
      net: 'rgba(110,220,200,0.32)', netGlow: '#34d4bd',
      gold: '#f5cf6a', goldDeep: '#dba83a',
      featTint: 'rgba(255,255,255,0.08)', featIcon: '#5eead4', featText: 'rgba(255,255,255,0.78)',
      pillBg: 'rgba(4,30,28,0.55)', pillBorder: 'rgba(245,207,106,0.35)', pillText: '#ffe49a',
      footerText: 'rgba(255,255,255,0.55)', footerSub: 'rgba(255,255,255,0.4)'
    },
    dark: {
      bgFrom: '#020f0e', bgVia: '#03201d', bgTo: '#053934',
      cardBg: 'rgba(14,32,30,0.78)', cardBorder: 'rgba(94,234,212,0.16)',
      text: '#e8fbf6', textMuted: '#8fbcb1', textSubtle: '#5a7e76',
      inputBg: 'rgba(4,18,16,0.6)', inputBorder: 'rgba(94,234,212,0.16)', inputBorderFocus: '#5eead4',
      btnFrom: '#0f766e', btnTo: '#2dd4bf', btnGlow: 'rgba(45,212,191,0.45)',
      net: 'rgba(110,220,200,0.28)', netGlow: '#34d4bd',
      gold: '#f5cf6a', goldDeep: '#dba83a',
      featTint: 'rgba(255,255,255,0.04)', featIcon: '#7eead4', featText: 'rgba(220,250,243,0.7)',
      pillBg: 'rgba(4,18,16,0.7)', pillBorder: 'rgba(245,207,106,0.3)', pillText: '#ffe49a',
      footerText: 'rgba(220,250,243,0.45)', footerSub: 'rgba(220,250,243,0.32)'
    }
  },
  royal: {
    light: {
      bgFrom: '#1a0a47', bgVia: '#2d1372', bgTo: '#4f2bae',
      cardBg: 'rgba(255,255,255,0.92)', cardBorder: 'rgba(255,255,255,0.6)',
      text: '#1a0a47', textMuted: '#574a78', textSubtle: '#8e87a8',
      inputBg: '#ffffff', inputBorder: '#e6e3f0', inputBorderFocus: '#7c3aed',
      btnFrom: '#6d28d9', btnTo: '#8b5cf6', btnGlow: 'rgba(139,92,246,0.45)',
      net: 'rgba(170,140,255,0.32)', netGlow: '#9d7bff',
      gold: '#f4c14a', goldDeep: '#d99820',
      featTint: 'rgba(255,255,255,0.08)', featIcon: '#c4b5fd', featText: 'rgba(255,255,255,0.78)',
      pillBg: 'rgba(20,10,55,0.55)', pillBorder: 'rgba(244,193,74,0.35)', pillText: '#ffd97a',
      footerText: 'rgba(255,255,255,0.55)', footerSub: 'rgba(255,255,255,0.4)'
    },
    dark: {
      bgFrom: '#0a0418', bgVia: '#150a35', bgTo: '#241354',
      cardBg: 'rgba(28,18,55,0.78)', cardBorder: 'rgba(196,181,253,0.16)',
      text: '#f3eeff', textMuted: '#b4a8d5', textSubtle: '#766b94',
      inputBg: 'rgba(12,6,30,0.6)', inputBorder: 'rgba(196,181,253,0.16)', inputBorderFocus: '#c4b5fd',
      btnFrom: '#5b21b6', btnTo: '#8b5cf6', btnGlow: 'rgba(139,92,246,0.45)',
      net: 'rgba(170,140,255,0.28)', netGlow: '#9d7bff',
      gold: '#f4c14a', goldDeep: '#d99820',
      featTint: 'rgba(255,255,255,0.04)', featIcon: '#c4b5fd', featText: 'rgba(243,238,255,0.7)',
      pillBg: 'rgba(12,6,30,0.7)', pillBorder: 'rgba(244,193,74,0.3)', pillText: '#ffd97a',
      footerText: 'rgba(243,238,255,0.45)', footerSub: 'rgba(243,238,255,0.32)'
    }
  }
};

// ─────────────────────────────────────────────────────────────
// Animated network background — buildings + nodes + flowing lines
// ─────────────────────────────────────────────────────────────
function NetworkBg({ p, speed = 1, paused = false, transparent = false }) {
  // Deterministic nodes
  const nodes = useMemo(() => {
    const seed = (s) => {let h = 2166136261;for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);return (h >>> 0) / 4294967295;};
    return Array.from({ length: 22 }, (_, i) => ({
      x: seed('x' + i) * 100,
      y: seed('y' + i) * 60 + (seed('yo' + i) > 0.5 ? 0 : 35),
      r: seed('r' + i) * 1.4 + 1.2,
      delay: seed('d' + i) * 6
    }));
  }, []);

  // Connections (pairs of nodes within distance)
  const links = useMemo(() => {
    const out = [];
    for (let i = 0; i < nodes.length; i++) {
      for (let j = i + 1; j < nodes.length; j++) {
        const dx = nodes[i].x - nodes[j].x,dy = nodes[i].y - nodes[j].y;
        const d = Math.hypot(dx, dy);
        if (d > 8 && d < 24) out.push({ a: i, b: j, d, delay: (i * 7 + j * 13) % 12 });
      }
    }
    return out.slice(0, 36);
  }, [nodes]);

  const dur = `${(14 / Math.max(0.2, speed)).toFixed(1)}s`;

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      {/* gradient base — skipped when transparent so the page bg shows through */}
      {!transparent && (
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, ${p.bgFrom} 0%, ${p.bgVia} 45%, ${p.bgTo} 100%)`
        }} />
      )}
      {/* soft top glow */}
      <div style={{
        position: 'absolute', top: '-15%', left: '50%', transform: 'translateX(-50%)',
        width: '140%', height: '55%',
        background: `radial-gradient(ellipse at center, ${p.netGlow}33, transparent 60%)`,
        filter: 'blur(20px)'
      }} />
      {/* bottom horizon glow */}
      <div style={{
        position: 'absolute', bottom: '-10%', left: '-10%', right: '-10%', height: '40%',
        background: `radial-gradient(ellipse at center, ${p.btnGlow}22, transparent 65%)`,
        filter: 'blur(30px)'
      }} />

      {/* Network SVG */}
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
        animationPlayState: paused ? 'paused' : 'running'
      }}>
        <defs>
          <linearGradient id="lineGrad" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor={p.net} stopOpacity="0" />
            <stop offset="50%" stopColor={p.netGlow} stopOpacity="0.9" />
            <stop offset="100%" stopColor={p.net} stopOpacity="0" />
          </linearGradient>
          <radialGradient id="nodeGrad">
            <stop offset="0%" stopColor={p.netGlow} stopOpacity="1" />
            <stop offset="100%" stopColor={p.netGlow} stopOpacity="0" />
          </radialGradient>
        </defs>

        {/* static thin links */}
        {links.map((l, i) => {
          const a = nodes[l.a],b = nodes[l.b];
          return (
            <line key={'s' + i} x1={a.x} y1={a.y} x2={b.x} y2={b.y}
            stroke={p.net} strokeWidth="0.08" opacity="0.6" />);

        })}

        {/* flowing pulses along links */}
        {links.slice(0, 18).map((l, i) => {
          const a = nodes[l.a],b = nodes[l.b];
          return (
            <circle key={'p' + i} r="0.5" fill={p.netGlow}
            style={{
              filter: `drop-shadow(0 0 0.6px ${p.netGlow})`,
              animation: `pulseAlong${i} ${dur} linear ${l.delay}s infinite`,
              animationPlayState: paused ? 'paused' : 'running'
            }}>
              <animate attributeName="cx" values={`${a.x};${b.x};${a.x}`} dur={dur} repeatCount="indefinite" begin={`${l.delay}s`} />
              <animate attributeName="cy" values={`${a.y};${b.y};${a.y}`} dur={dur} repeatCount="indefinite" begin={`${l.delay}s`} />
              <animate attributeName="opacity" values="0;1;1;0" dur={dur} repeatCount="indefinite" begin={`${l.delay}s`} />
            </circle>);

        })}

        {/* nodes */}
        {nodes.map((n, i) =>
        <g key={'n' + i}>
            <circle cx={n.x} cy={n.y} r={n.r * 0.8} fill={p.netGlow}
          opacity="0.9"
          style={{ animation: `nodePulse 4s ease-in-out ${n.delay}s infinite`, animationPlayState: paused ? 'paused' : 'running' }} />
            <circle cx={n.x} cy={n.y} r={n.r * 2.2} fill="url(#nodeGrad)" opacity="0.4" />
          </g>
        )}
      </svg>

      {/* Building silhouettes — left */}
      <svg viewBox="0 0 200 400" preserveAspectRatio="xMinYMax meet" style={{
        position: 'absolute', left: -10, bottom: '32%', width: '42%', height: '40%',
        opacity: 0.55, pointerEvents: 'none'
      }}>
        <defs>
          <linearGradient id="bldL" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={p.bgTo} stopOpacity="0" />
            <stop offset="40%" stopColor="#000" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#000" stopOpacity="0.7" />
          </linearGradient>
        </defs>
        {/* buildings */}
        <rect x="10" y="120" width="38" height="280" fill="url(#bldL)" />
        <rect x="52" y="60" width="44" height="340" fill="url(#bldL)" />
        <rect x="100" y="140" width="34" height="260" fill="url(#bldL)" />
        <rect x="138" y="100" width="40" height="300" fill="url(#bldL)" />
        {/* windows — twinkle */}
        {Array.from({ length: 70 }).map((_, i) => {
          const bx = [12, 54, 102, 140][i % 4];
          const bw = [38, 44, 34, 40][i % 4];
          const col = Math.floor(i / 14);
          const row = i % 14;
          return (
            <rect key={'wl' + i}
            x={bx + 4 + col * (bw - 12) / 3}
            y={150 + row * 18}
            width="3" height="5"
            fill={p.gold}
            opacity={i * 37 % 7 < 5 ? 0.55 : 0.15}
            style={{ animation: `winFlick 6s ease-in-out ${i % 9 * 0.7}s infinite`, animationPlayState: paused ? 'paused' : 'running' }} />);


        })}
      </svg>

      {/* mirrored right side — graph chart */}
      <svg viewBox="0 0 200 400" preserveAspectRatio="xMaxYMax meet" style={{
        position: 'absolute', right: -10, bottom: '30%', width: '42%', height: '38%',
        opacity: 0.55, pointerEvents: 'none'
      }}>
        <defs>
          <linearGradient id="bldR" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={p.bgTo} stopOpacity="0" />
            <stop offset="40%" stopColor="#000" stopOpacity="0.3" />
            <stop offset="100%" stopColor="#000" stopOpacity="0.65" />
          </linearGradient>
        </defs>
        {/* bar chart silhouette */}
        <rect x="20" y="280" width="22" height="120" fill="url(#bldR)" />
        <rect x="48" y="240" width="22" height="160" fill="url(#bldR)" />
        <rect x="76" y="200" width="22" height="200" fill="url(#bldR)" />
        <rect x="104" y="160" width="22" height="240" fill="url(#bldR)" />
        <rect x="132" y="120" width="22" height="280" fill="url(#bldR)" />
        <rect x="160" y="80" width="22" height="320" fill="url(#bldR)" />
        {/* trend line */}
        <polyline points="30,290 60,250 90,210 120,170 150,130 175,90"
        fill="none" stroke={p.netGlow} strokeWidth="1.5" strokeLinecap="round" opacity="0.8" />
        {[[30, 290], [60, 250], [90, 210], [120, 170], [150, 130], [175, 90]].map(([x, y], i) =>
        <circle key={'tr' + i} cx={x} cy={y} r="3" fill={p.netGlow}
        style={{ animation: `nodePulse 3.5s ease-in-out ${i * 0.4}s infinite`, animationPlayState: paused ? 'paused' : 'running' }} />
        )}
      </svg>

      {/* gold diagonal accents */}
      <div style={{
        position: 'absolute', left: -20, top: '46%',
        width: 140, height: 1, background: `linear-gradient(90deg, transparent, ${p.gold}, transparent)`,
        transform: 'rotate(-22deg)', opacity: 0.6
      }} />
      <div style={{
        position: 'absolute', right: -20, top: '40%',
        width: 160, height: 1, background: `linear-gradient(90deg, transparent, ${p.gold}, transparent)`,
        transform: 'rotate(22deg)', opacity: 0.55
      }} />
    </div>);

}

// ─────────────────────────────────────────────────────────────
// SC AccountPro — fully native SVG brand mark
// Geometric SC monogram + neural circuit mesh + animated nodes,
// ACCOUNTPRO wordmark, gold accent rule, AI badge.
// No PNG — everything is animatable SVG/CSS.
// ─────────────────────────────────────────────────────────────
function SCLogo({ p, paused = false, font = 'Bodoni Moda' }) {
  const NAVY      = '#0e1f44';
  const NAVY_MID  = '#1d3766';
  const NAVY_LT   = '#3a5e9e';
  const GOLD      = p.gold || '#e8a834';
  const GOLD_DK   = p.goldDeep || '#b87d12';
  const CYAN      = '#7eb6ff';
  const BLUE      = '#3b82f6';

  // Per-font size/weight/letter-spacing tuning so different families sit nicely
  const fontTuning = {
    'Bodoni Moda':         { size: 105, weight: 900, ls: -5 },
    'Playfair Display':    { size: 110, weight: 900, ls: -5 },
    'Cinzel':              { size: 95,  weight: 900, ls: -3 },
    'Cormorant Garamond':  { size: 118, weight: 700, ls: -7 },
    'DM Serif Display':    { size: 110, weight: 400, ls: -5 },
    'Abril Fatface':       { size: 105, weight: 400, ls: -5 },
    'Yeseva One':          { size: 108, weight: 400, ls: -4 },
    'Libre Bodoni':        { size: 108, weight: 900, ls: -5 },
    'EB Garamond':         { size: 118, weight: 700, ls: -7 },
    'Cardo':               { size: 118, weight: 700, ls: -7 },
    'Spectral SC':         { size: 92,  weight: 800, ls: 0 },
    'Marcellus':           { size: 108, weight: 400, ls: -3 },
    'Italiana':            { size: 130, weight: 400, ls: -7 },
    'Inter':               { size: 100, weight: 800, ls: -7 },
    'Bebas Neue':          { size: 130, weight: 400, ls: 0 },
    'Oswald':              { size: 118, weight: 700, ls: -3 },
    'Anton':               { size: 122, weight: 400, ls: -3 },
    'Archivo Black':       { size: 100, weight: 400, ls: -5 },
    'Russo One':           { size: 100, weight: 400, ls: -3 },
    'Big Shoulders Display': { size: 130, weight: 900, ls: -5 },
    'Audiowide':           { size: 92,  weight: 400, ls: 0 },
    'Orbitron':            { size: 95,  weight: 900, ls: -3 },
    'Krona One':           { size: 92,  weight: 400, ls: 0 },
    'Michroma':            { size: 76,  weight: 400, ls: 0 },
    'Major Mono Display':  { size: 92,  weight: 400, ls: -3 },
    'Syncopate':           { size: 84,  weight: 700, ls: 0 },
    'Iceland':             { size: 130, weight: 400, ls: -5 },
    'Wallpoet':            { size: 100, weight: 400, ls: 0 },
    'Black Ops One':       { size: 108, weight: 400, ls: -3 },
    'Bungee':              { size: 92,  weight: 400, ls: -3 },
    'Stalinist One':       { size: 92,  weight: 400, ls: -3 },
    'Limelight':           { size: 102, weight: 400, ls: -3 },
    'Monoton':             { size: 108, weight: 400, ls: -3 },
    'Faster One':          { size: 118, weight: 400, ls: -5 },
    'Tangerine':           { size: 170, weight: 700, ls: -5 },
    'Great Vibes':         { size: 140, weight: 400, ls: -5 },
    'Allura':              { size: 140, weight: 400, ls: -5 },
    'Pinyon Script':       { size: 140, weight: 400, ls: -5 },
  };
  const ft = fontTuning[font] || fontTuning['Bodoni Moda'];
  const FS = ft.size;
  const FW = ft.weight;
  const LS = ft.ls;
  const FAM = `"${font}", "Bodoni Moda", "Playfair Display", serif`;

  // Hex grid pattern for the neural side
  const hexNodes = [
    { x: 178, y: 70,  r: 3.6, d: 0    },
    { x: 198, y: 55,  r: 2.4, d: 0.4  },
    { x: 218, y: 75,  r: 3,   d: 0.8  },
    { x: 195, y: 92,  r: 2.6, d: 0.2  },
    { x: 215, y: 110, r: 3.2, d: 1.0  },
    { x: 190, y: 128, r: 2.4, d: 1.3  },
    { x: 175, y: 110, r: 3,   d: 0.6  },
    { x: 230, y: 95,  r: 2.2, d: 1.5  },
    { x: 168, y: 88,  r: 2.6, d: 1.8  },
  ];
  const hexEdges = [
    [0,1],[1,2],[2,4],[4,5],[5,6],[6,0],[0,3],[3,1],[3,4],[3,6],[2,7],[4,7],[0,8],[6,8],[3,8],
  ];

  return (
    <div style={{
      position: 'relative',
      width: 290, height: 200,
      overflow: 'visible',
      background: 'transparent',
    }}>

      {/* === Ambient glow — pure circular, no rectangular bounds === */}
      <div style={{
        position: 'absolute',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 460, height: 460,
        pointerEvents: 'none',
        borderRadius: '50%',
        background: `radial-gradient(circle, rgba(56,121,238,0.10) 0%, rgba(56,121,238,0.05) 30%, transparent 65%)`,
        filter: 'blur(28px)',
        animation: 'haloPulse 6s ease-in-out infinite',
        animationPlayState: paused ? 'paused' : 'running',
        zIndex: 0,
      }} />
      <div style={{
        position: 'absolute',
        top: '60%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 380, height: 380,
        pointerEvents: 'none',
        borderRadius: '50%',
        background: `radial-gradient(circle, rgba(244,193,74,0.07) 0%, rgba(244,193,74,0.03) 30%, transparent 65%)`,
        filter: 'blur(32px)',
        animation: 'haloPulse 6s ease-in-out 1.5s infinite',
        animationPlayState: paused ? 'paused' : 'running',
        zIndex: 0,
      }} />

      {/* === Floating ambient particles === */}
      <svg viewBox="0 0 290 200" preserveAspectRatio="none" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none',
      }}>
        <defs>
          <radialGradient id="amb1"><stop offset="0%" stopColor={CYAN} stopOpacity="0.9"/><stop offset="100%" stopColor={CYAN} stopOpacity="0"/></radialGradient>
        </defs>
        {[
          [22, 18, 0],[42, 36, 0.6],[24, 165, 1.2],[58, 178, 0.3],
          [265, 24, 0.8],[252, 168, 1.4],[270, 92, 0.5],[12, 96, 1.6],
        ].map(([x,y,d], i) => (
          <g key={`amb-${i}`} style={{
            transformOrigin: `${x}px ${y}px`,
            animation: `nodePulse 3s ease-in-out ${d}s infinite, partFloat 5s ease-in-out ${d * 0.3}s infinite`,
            animationPlayState: paused ? 'paused' : 'running',
          }}>
            <circle cx={x} cy={y} r="5" fill="url(#amb1)" />
            <circle cx={x} cy={y} r="1.2" fill={CYAN} />
          </g>
        ))}
      </svg>

      {/* === MAIN COMPOSITION === */}
      <svg viewBox="0 0 290 200" width="290" height="200" style={{
        position: 'relative', zIndex: 2, overflow: 'visible',
      }}>
        <defs>
          {/* Gold metallic — softened to blend with navy bg */}
          <linearGradient id="goldFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"  stopColor="#ffe9b0" />
            <stop offset="22%" stopColor="#f4c97a" />
            <stop offset="50%" stopColor={GOLD} />
            <stop offset="78%" stopColor={GOLD_DK} />
            <stop offset="100%" stopColor="#6a4310" />
          </linearGradient>
          {/* Steel/silver for C — softer top so it doesn't pop against dark navy */}
          <linearGradient id="silverFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"  stopColor="#c8d5ee" />
            <stop offset="35%" stopColor="#8fa6d0" />
            <stop offset="60%" stopColor="#4a6aa8" />
            <stop offset="100%" stopColor="#1a2f5c" />
          </linearGradient>
          {/* Wordmark gradient */}
          <linearGradient id="wordFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"  stopColor="#eaf0ff" />
            <stop offset="100%" stopColor="#9bb6e8" />
          </linearGradient>
          {/* Cyan glow for nodes */}
          <radialGradient id="cyanGlow">
            <stop offset="0%" stopColor={CYAN} stopOpacity="1" />
            <stop offset="60%" stopColor={BLUE} stopOpacity="0.35" />
            <stop offset="100%" stopColor={BLUE} stopOpacity="0" />
          </radialGradient>
          {/* Shine sweep */}
          <linearGradient id="shineSweep" x1="-1" y1="0" x2="1" y2="0">
            <stop offset="0%"   stopColor="#fff" stopOpacity="0" />
            <stop offset="45%"  stopColor="#fff" stopOpacity="0.85" />
            <stop offset="55%"  stopColor="#fff" stopOpacity="0.85" />
            <stop offset="100%" stopColor="#fff" stopOpacity="0" />
          </linearGradient>
          {/* Drop shadow */}
          <filter id="lgDrop" x="-30%" y="-30%" width="160%" height="160%">
            <feDropShadow dx="1" dy="2" stdDeviation="4" floodColor="#0a1a3f" floodOpacity="0.35" />
          </filter>
          {/* Letter masks for shimmer overlay */}
          <mask id="maskS">
            <text x="85" y="106" textAnchor="middle"
              fontFamily={FAM}
              fontSize={FS} fontWeight={FW} letterSpacing={LS} fill="white">S</text>
          </mask>
          <mask id="maskC">
            <text x="147" y="106" textAnchor="middle"
              fontFamily={FAM}
              fontSize={FS} fontWeight={FW} letterSpacing={LS} fill="white">C</text>
          </mask>
        </defs>

        {/* ─── Decorative concentric hex rings on the right (AI side) ─── */}
        <g opacity="0.4">
          <circle cx="200" cy="95" r="45" fill="none" stroke={CYAN} strokeWidth="0.5" strokeDasharray="2 3"
            style={{ animation: 'spinSlow 28s linear infinite', animationPlayState: paused ? 'paused' : 'running', transformOrigin: '200px 95px' }} />
          <circle cx="200" cy="95" r="58" fill="none" stroke={NAVY_LT} strokeWidth="0.5" strokeDasharray="1 5" />
          <circle cx="200" cy="95" r="72" fill="none" stroke={CYAN} strokeWidth="0.4" strokeDasharray="1 8"
            style={{ animation: 'spinSlow 40s linear reverse infinite', animationPlayState: paused ? 'paused' : 'running', transformOrigin: '200px 95px' }} />
        </g>

        {/* ─── Neural mesh on the right (AI face area) ─── */}
        {/* edges */}
        {hexEdges.map(([a,b], i) => (
          <line key={`he-${i}`}
            x1={hexNodes[a].x} y1={hexNodes[a].y}
            x2={hexNodes[b].x} y2={hexNodes[b].y}
            stroke={CYAN} strokeWidth="0.6" opacity="0.55" />
        ))}
        {/* nodes */}
        {hexNodes.map((n, i) => (
          <g key={`hn-${i}`} style={{
            transformOrigin: `${n.x}px ${n.y}px`,
            animation: `nodePulse 2.6s ease-in-out ${n.d}s infinite`,
            animationPlayState: paused ? 'paused' : 'running',
          }}>
            <circle cx={n.x} cy={n.y} r={n.r * 2.2} fill="url(#cyanGlow)" />
            <circle cx={n.x} cy={n.y} r={n.r} fill={CYAN} />
            <circle cx={n.x} cy={n.y} r={n.r * 0.35} fill="#fff" opacity="0.95" />
          </g>
        ))}

        {/* AI badge removed */}

        {/* ─── S (gold 3D, in front) ─── */}
        <g filter="url(#lgDrop)">
          {/* dark underlay for depth — soft + low contrast */}
          <text x="86" y="108" textAnchor="middle"
            fontFamily={FAM}
            fontSize={FS} fontWeight={FW} letterSpacing={LS}
            fill="#2a1a05" opacity="0.55">S</text>
          {/* main gold */}
          <text x="85" y="106" textAnchor="middle"
            fontFamily={FAM}
            fontSize={FS} fontWeight={FW} letterSpacing={LS}
            fill="url(#goldFill)">S</text>
        </g>
        {/* shimmer over S — softened opacity to match ambient light */}
        <g mask="url(#maskS)">
          <rect x="-200" y="20" width="160" height="100" fill="url(#shineSweep)" opacity="0.5"
            style={{ animation: 'shimmerWide 5.5s ease-in-out 0.1s infinite', animationPlayState: paused ? 'paused' : 'running' }} />
        </g>

        {/* ─── C (silver/steel, behind on right) ─── */}
        <g filter="url(#lgDrop)">
          <text x="148" y="108" textAnchor="middle"
            fontFamily={FAM}
            fontSize={FS} fontWeight={FW} letterSpacing={LS}
            fill="#0a1a3a" opacity="0.6">C</text>
          <text x="147" y="106" textAnchor="middle"
            fontFamily={FAM}
            fontSize={FS} fontWeight={FW} letterSpacing={LS}
            fill="url(#silverFill)">C</text>
        </g>
        {/* shimmer over C */}
        <g mask="url(#maskC)">
          <rect x="-200" y="20" width="160" height="100" fill="url(#shineSweep)" opacity="0.45"
            style={{ animation: 'shimmerWide 5.5s ease-in-out 0.6s infinite', animationPlayState: paused ? 'paused' : 'running' }} />
        </g>

        {/* ─── Gold pillar accent inside C (subtle building hint) ─── */}
        <g transform="translate(142, 80)">
          <rect x="0" y="0" width="6" height="28" rx="1" fill="url(#goldFill)" />
          <rect x="0" y="0" width="6" height="2" fill="#fff" opacity="0.5" />
          <path d="M -1 0 L 3 -4 L 7 0 Z" fill={GOLD_DK} />
        </g>

        {/* ─── Gold accent rule under SC ─── */}
        <line x1="75" y1="138" x2="175" y2="138" stroke="url(#goldFill)" strokeWidth="2.2" strokeLinecap="round" />
        <circle cx="125" cy="138" r="2.4" fill={GOLD} />
        <circle cx="125" cy="138" r="0.9" fill="#fff" />

        {/* ─── ACCOUNTPRO wordmark ─── */}
        <text x="145" y="166" textAnchor="middle"
          fontFamily='"Archivo Black", "Anton", system-ui, sans-serif'
          fontSize="22" fontWeight="900" letterSpacing="1.5"
          style={{ filter: 'drop-shadow(0 2px 3px rgba(0,0,0,0.5))' }}>
          <tspan fill="url(#wordFill)">ACCOUNT</tspan>
          <tspan fill="url(#goldFill)">PRO</tspan>
        </text>

        {/* ─── Thai tagline ─── */}
        <text x="145" y="184" textAnchor="middle"
          fontFamily='"IBM Plex Sans Thai", "Sukhumvit Set", sans-serif'
          fontSize="9.5" fontWeight="500"
          fill="rgba(220,232,255,0.85)" letterSpacing="0.3">
          <tspan>ระบบบัญชี </tspan>
          <tspan fill={GOLD} fontWeight="800">AI</tspan>
          <tspan> สำหรับสำนักงานบัญชีไทย</tspan>
        </text>

        {/* ─── Tiny side rules around tagline ─── */}
        <line x1="42" y1="181" x2="62" y2="181" stroke={GOLD} strokeWidth="0.9" opacity="0.7" />
        <line x1="228" y1="181" x2="248" y2="181" stroke={GOLD} strokeWidth="0.9" opacity="0.7" />

        {/* ─── Sparkles ─── */}
        <g transform="translate(195, 38)" style={{
          animation: 'sparkle 2.8s ease-in-out infinite',
          animationPlayState: paused ? 'paused' : 'running',
          transformOrigin: 'center',
        }}>
          <circle r="7" fill="#fff" opacity="0.3" style={{ filter: 'blur(2px)' }} />
          <path d="M0 -8 L 1.5 -1.5 L 8 0 L 1.5 1.5 L 0 8 L -1.5 1.5 L -8 0 L -1.5 -1.5 Z" fill="#fff" />
        </g>
        <g transform="translate(67, 132)" style={{
          animation: 'sparkle 2.8s ease-in-out 1.3s infinite',
          animationPlayState: paused ? 'paused' : 'running',
          transformOrigin: 'center',
        }}>
          <path d="M0 -4 L 0.8 -0.8 L 4 0 L 0.8 0.8 L 0 4 L -0.8 0.8 L -4 0 L -0.8 -0.8 Z" fill={GOLD} />
        </g>
      </svg>

      {/* === Corner brackets removed for seamless blend === */}

      {/* === Diagonal shine sweep removed (no tile to shine on) === */}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Inline icons
// ─────────────────────────────────────────────────────────────
const Icons = {
  shield: (c) =>
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <path d="M12 2.5L4 5.5v6c0 4.5 3.2 8.5 8 10 4.8-1.5 8-5.5 8-10v-6l-8-3z" stroke={c} strokeWidth="1.6" strokeLinejoin="round" />
      <path d="M9 12.5l2 2 4-4.5" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>,

  mail: (c) =>
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <rect x="3" y="5.5" width="18" height="13" rx="2" stroke={c} strokeWidth="1.7" />
      <path d="M3.5 7l8.5 6 8.5-6" stroke={c} strokeWidth="1.7" strokeLinejoin="round" />
    </svg>,

  lock: (c) =>
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <rect x="4" y="10" width="16" height="11" rx="2.5" stroke={c} strokeWidth="1.7" />
      <path d="M8 10V7a4 4 0 018 0v3" stroke={c} strokeWidth="1.7" strokeLinecap="round" />
      <circle cx="12" cy="15.5" r="1.4" fill={c} />
    </svg>,

  eye: (c) =>
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M2.5 12s3.5-6.5 9.5-6.5S21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z" stroke={c} strokeWidth="1.7" />
      <circle cx="12" cy="12" r="2.8" stroke={c} strokeWidth="1.7" />
    </svg>,

  eyeOff: (c) =>
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M3 3l18 18" stroke={c} strokeWidth="1.7" strokeLinecap="round" />
      <path d="M9.5 6.2C10.3 6.07 11.13 6 12 6c6 0 9.5 6.5 9.5 6.5a18.4 18.4 0 01-3.1 3.9M6.6 7.6C3.7 9.6 2.5 12 2.5 12S6 18.5 12 18.5c1.5 0 2.86-.36 4.05-.93" stroke={c} strokeWidth="1.7" strokeLinecap="round" />
      <path d="M14.1 14.1A3 3 0 019.9 9.9" stroke={c} strokeWidth="1.7" strokeLinecap="round" />
    </svg>,

  chip: (c) =>
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
      <rect x="6" y="6" width="12" height="12" rx="2" stroke={c} strokeWidth="1.8" />
      <rect x="9" y="9" width="6" height="6" rx="1" fill={c} opacity="0.4" />
      {[3, 12, 21].map((y, i) => <React.Fragment key={i}>
        <line x1="0" y1={y / 1.5 + 5} x2="6" y2={y / 1.5 + 5} stroke={c} strokeWidth="1.6" />
        <line x1="18" y1={y / 1.5 + 5} x2="24" y2={y / 1.5 + 5} stroke={c} strokeWidth="1.6" />
        <line x1={y / 1.5 + 5} y1="0" x2={y / 1.5 + 5} y2="6" stroke={c} strokeWidth="1.6" />
        <line x1={y / 1.5 + 5} y1="18" x2={y / 1.5 + 5} y2="24" stroke={c} strokeWidth="1.6" />
      </React.Fragment>)}
    </svg>,

  doc: (c) =>
  <svg width="38" height="38" viewBox="0 0 32 32" fill="none">
      {/* Document outline */}
      <path d="M8 3 H 18 L 24 9 V 28 a 1 1 0 0 1 -1 1 H 8 a 1 1 0 0 1 -1 -1 V 4 a 1 1 0 0 1 1 -1 z" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M18 3 V 9 H 24" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      {/* "AI" badge inside document (small filled box) */}
      <rect x="10" y="20" width="9" height="6" rx="0.8" fill={c}/>
      <text x="14.5" y="24.7" textAnchor="middle" fontSize="4.5" fontWeight="800" fill="#0a1c45" fontFamily="Inter, sans-serif">AI</text>
    </svg>,

  chart: (c) =>
  <svg width="38" height="38" viewBox="0 0 32 32" fill="none">
      {/* Bars — outline */}
      <rect x="5" y="20" width="4" height="9"  rx="0.6" stroke={c} strokeWidth="1.4" fill="none"/>
      <rect x="11" y="16" width="4" height="13" rx="0.6" stroke={c} strokeWidth="1.4" fill="none"/>
      <rect x="17" y="12" width="4" height="17" rx="0.6" stroke={c} strokeWidth="1.4" fill="none"/>
      <rect x="23" y="7"  width="4" height="22" rx="0.6" stroke={c} strokeWidth="1.4" fill="none"/>
      {/* Trend arrow up */}
      <path d="M5 11 L 13 7 L 19 10 L 27 4" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      <path d="M22 4 L 27 4 L 27 9" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
    </svg>,

  shieldFeat: (c) =>
  <svg width="38" height="38" viewBox="0 0 32 32" fill="none">
      {/* Shield outline */}
      <path d="M16 3 L 6 6.5 v 8 c 0 6.2 4.2 11.5 10 13 5.8-1.5 10-6.8 10-13 V 6.5 L 16 3 z" stroke={c} strokeWidth="1.6" strokeLinejoin="round" fill="none"/>
      {/* Check mark */}
      <path d="M11 15.5 l 3.5 3.5 L 21 12.5" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
    </svg>,

  cloud: (c) =>
  <svg width="38" height="38" viewBox="0 0 32 32" fill="none">
      {/* Cloud outline */}
      <path d="M9 24 a 5.5 5.5 0 0 1 -1 -10.9 a 7.5 7.5 0 0 1 14.6 1.4 a 4.8 4.8 0 0 1 0.4 9.5 H 9 z" stroke={c} strokeWidth="1.6" strokeLinejoin="round" fill="none"/>
    </svg>

};

// ─────────────────────────────────────────────────────────────
// Login Screen
// ─────────────────────────────────────────────────────────────
function LoginScreen({ tweaks, animPaused }) {
  const p = PALETTES[tweaks.accent][tweaks.dark ? 'dark' : 'light'];

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [remember, setRemember] = useState(true);
  const [focused, setFocused] = useState(null);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [errors, setErrors] = useState({});
  const [showForgot, setShowForgot] = useState(false);

  // ─── Load remembered email ตอน mount (Option A — Auto-fill email) ───
  useEffect(() => {
    try {
      const savedEmail = localStorage.getItem('remember_email');
      if (savedEmail) {
        setEmail(savedEmail);
        setRemember(true);
      } else {
        // ถ้าไม่มี · ค่า default remember = false (ไม่บังคับ)
        setRemember(false);
      }
    } catch (e) { /* localStorage ใช้ไม่ได้ — ignore */ }
  }, []);

  const blurAmt = tweaks.glass; // 0..24

  const onSubmit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!email) errs.email = 'กรุณากรอกอีเมล';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errs.email = 'รูปแบบอีเมลไม่ถูกต้อง';
    if (!password) errs.password = 'กรุณากรอกรหัสผ่าน';
    else if (password.length < 6) errs.password = 'รหัสผ่านอย่างน้อย 6 ตัวอักษร';
    setErrors(errs);
    if (Object.keys(errs).length) return;

    setLoading(true);
    try {
      if (!window.api) throw new Error('API client ไม่พร้อม — รีเฟรชหน้าใหม่');
      await window.api.login(email, password);
      // ─── Save / clear remembered email ตามที่ ติ๊ก "จำฉันไว้" ───
      try {
        if (remember) localStorage.setItem('remember_email', email);
        else localStorage.removeItem('remember_email');
      } catch (e) { /* ignore */ }
      setLoading(false);
      setSuccess(true);
      setTimeout(() => { window.location.href = '/static/dashboard.html'; }, 600);
    } catch (err) {
      setLoading(false);
      setErrors({ password: err.message || 'เข้าสู่ระบบไม่สำเร็จ — ตรวจ email/password อีกครั้ง' });
    }
  };

  const inputStyle = (key) => ({
    width: '100%', boxSizing: 'border-box',
    background: p.inputBg,
    border: `1.5px solid ${errors[key] ? '#ef4444' : focused === key ? p.inputBorderFocus : p.inputBorder}`,
    borderRadius: 14, padding: '12px 14px 12px 50px',
    fontSize: 15, color: p.text,
    outline: 'none', transition: 'all .18s ease',
    boxShadow: focused === key ?
    `0 0 0 4px ${p.inputBorderFocus}26, 0 2px 8px ${p.inputBorderFocus}15` :
    '0 1px 2px rgba(0,0,0,0.03)',
    fontFamily: 'inherit'
  });

  return (
    <div style={{
      position: 'relative', height: '100%', width: '100%',
      overflow: tweaks.showFrame ? 'hidden' : 'visible',
      fontFamily: '"Sukhumvit Set","IBM Plex Sans Thai","Noto Sans Thai",-apple-system,system-ui,sans-serif',
      color: '#fff'
    }}>
      {tweaks.showFrame && (
        <NetworkBg p={p} speed={tweaks.speed} paused={animPaused} transparent={!tweaks.showFrame} />
      )}

      {/* LINE webview header removed */}

      {/* Scrollable content */}
      <div style={{
        position: 'relative', zIndex: 5,
        height: '100%', overflowY: 'auto',
        padding: '24px 20px 18px',
        display: 'flex', flexDirection: 'column', alignItems: 'center'
      }}>
        {/* Logo */}
        <SCLogo p={p} paused={animPaused} font={tweaks.logoFont} />

        {/* AI POWERED pill */}
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '5px 12px 5px 8px',
          background: p.pillBg,
          border: `1px solid ${p.pillBorder}`,
          borderRadius: 999,
          backdropFilter: `blur(${Math.max(4, blurAmt)}px) saturate(140%)`,
          WebkitBackdropFilter: `blur(${Math.max(4, blurAmt)}px) saturate(140%)`,
          marginTop: 8,
          marginBottom: 10,
          boxShadow: `0 4px 16px rgba(0,0,0,0.2), inset 0 1px 0 rgba(255,255,255,0.08)`
        }}>
          <div style={{
            width: 20, height: 20, borderRadius: 5,
            background: `linear-gradient(135deg, ${p.gold}, ${p.goldDeep})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: `0 0 8px ${p.gold}66`
          }}>
            {Icons.chip('#0a2358')}
          </div>
          <span style={{
            color: p.pillText, fontSize: 11, fontWeight: 700,
            letterSpacing: 1.3, textTransform: 'uppercase', whiteSpace: 'nowrap'
          }}>AI Powered Accounting</span>
        </div>

        {/* Glass Login Card */}
        <form onSubmit={onSubmit} style={{
          width: '100%', maxWidth: 380,
          background: p.cardBg,
          border: `1px solid ${p.cardBorder}`,
          borderRadius: 22,
          padding: '18px 20px 18px',
          backdropFilter: `blur(${blurAmt}px) saturate(180%)`,
          WebkitBackdropFilter: `blur(${blurAmt}px) saturate(180%)`,
          boxShadow: `
            0 20px 50px rgba(0,0,0,0.25),
            0 0 0 1px ${p.cardBorder},
            inset 0 1px 0 rgba(255,255,255,0.5)
          `,
          position: 'relative'
        }}>
          {/* lock badge */}
          <div style={{
            display: 'flex', justifyContent: 'center', marginTop: -2, marginBottom: 8
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 14,
              background: tweaks.dark ?
              `linear-gradient(135deg, ${p.inputBorderFocus}22, ${p.inputBorderFocus}10)` :
              `linear-gradient(135deg, #dbeafe, #eff6ff)`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `1px solid ${p.inputBorderFocus}33`,
              boxShadow: `0 6px 16px ${p.inputBorderFocus}22, inset 0 1px 0 rgba(255,255,255,0.5)`
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                <path d="M5 4l7-2.5L19 4v6.5c0 5-3.5 9.5-7 11-3.5-1.5-7-6-7-11V4z"
                stroke={p.inputBorderFocus} strokeWidth="1.6" strokeLinejoin="round" fill={`${p.inputBorderFocus}10`} />
                <rect x="9" y="10" width="6" height="6" rx="1.4" fill={p.inputBorderFocus} />
                <path d="M10.2 10V8.5a1.8 1.8 0 013.6 0V10" stroke={p.inputBorderFocus} strokeWidth="1.6" strokeLinecap="round" />
              </svg>
            </div>
          </div>

          {!success ? <>
            <div style={{
              textAlign: 'center', fontSize: 22, fontWeight: 800, color: p.text,
              letterSpacing: -0.3, marginBottom: 2
            }}>เข้าสู่ระบบ</div>
            <div style={{
              textAlign: 'center', fontSize: 12.5, color: p.textMuted, marginBottom: 14
            }}>ยินดีต้อนรับสู่ SC AccountPro</div>

            {/* Email */}
            <label style={{ display: 'block', position: 'relative', marginBottom: 10 }}>
              <div style={{
                position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                color: focused === 'email' ? p.inputBorderFocus : p.textSubtle,
                transition: 'color .18s'
              }}>{Icons.mail(focused === 'email' ? p.inputBorderFocus : p.textSubtle)}</div>
              <div style={{
                position: 'absolute', left: 50, top: 9,
                fontSize: 11, fontWeight: 700, color: p.text, letterSpacing: 0.2
              }}>Email</div>
              <input
                type="email"
                value={email}
                onChange={(e) => {setEmail(e.target.value);if (errors.email) setErrors({ ...errors, email: null });}}
                onFocus={() => setFocused('email')}
                onBlur={() => setFocused(null)}
                placeholder="example@company.com"
                style={{ ...inputStyle('email'), padding: '22px 14px 8px 46px' }}
                autoComplete="email" />
              
              {errors.email &&
              <div style={{ color: '#ef4444', fontSize: 11.5, marginTop: 6, marginLeft: 4 }}>{errors.email}</div>
              }
            </label>

            {/* Password */}
            <label style={{ display: 'block', position: 'relative', marginBottom: 12 }}>
              <div style={{
                position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                color: focused === 'password' ? p.inputBorderFocus : p.textSubtle,
                transition: 'color .18s'
              }}>{Icons.lock(focused === 'password' ? p.inputBorderFocus : p.textSubtle)}</div>
              <div style={{
                position: 'absolute', left: 50, top: 9,
                fontSize: 11, fontWeight: 700, color: p.text, letterSpacing: 0.2
              }}>Password</div>
              <input
                type={showPw ? 'text' : 'password'}
                value={password}
                onChange={(e) => {setPassword(e.target.value);if (errors.password) setErrors({ ...errors, password: null });}}
                onFocus={() => setFocused('password')}
                onBlur={() => setFocused(null)}
                placeholder="กรอกรหัสผ่าน"
                style={{ ...inputStyle('password'), padding: '22px 44px 8px 46px' }}
                autoComplete="current-password" />
              
              <button type="button" onClick={() => setShowPw(!showPw)} style={{
                position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
                background: 'transparent', border: 'none', cursor: 'pointer', padding: 6,
                color: p.textSubtle, display: 'flex'
              }}>{showPw ? Icons.eyeOff(p.textSubtle) : Icons.eye(p.textSubtle)}</button>
              {errors.password &&
              <div style={{ color: '#ef4444', fontSize: 11.5, marginTop: 6, marginLeft: 4 }}>{errors.password}</div>
              }
            </label>

            {/* Remember / forgot */}
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              marginBottom: 14, fontSize: 13
            }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', color: p.text }}>
                <button type="button" onClick={() => setRemember(!remember)} style={{
                  width: 18, height: 18, borderRadius: 5,
                  border: `1.6px solid ${remember ? p.inputBorderFocus : p.inputBorder}`,
                  background: remember ? p.inputBorderFocus : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  padding: 0, cursor: 'pointer', transition: 'all .15s'
                }} aria-pressed={remember}>
                  {remember &&
                  <svg width="11" height="11" viewBox="0 0 12 12">
                      <path d="M2 6.5 L 5 9 L 10 3" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  }
                </button>
                <span>จำฉันไว้</span>
              </label>
              <a href="#" onClick={(e) => { e.preventDefault(); setShowForgot(true); }} style={{
                color: p.inputBorderFocus, fontWeight: 600, textDecoration: 'none', cursor: 'pointer'
              }}>ลืมรหัสผ่าน?</a>
            </div>

            {/* Login button */}
            <button type="submit" disabled={loading} style={{
              width: '100%', height: 48, borderRadius: 14, border: 'none',
              background: `linear-gradient(135deg, ${p.btnFrom}, ${p.btnTo})`,
              color: '#fff', fontSize: 15.5, fontWeight: 700,
              cursor: loading ? 'wait' : 'pointer', whiteSpace: 'nowrap',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: `0 8px 22px ${p.btnGlow}, inset 0 1px 0 rgba(255,255,255,0.25), inset 0 -2px 0 rgba(0,0,0,0.12)`,
              transition: 'transform .12s, box-shadow .18s',
              fontFamily: 'inherit', position: 'relative', overflow: 'hidden'
            }}
            onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.98)'}
            onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
              
              {loading ?
              <>
                  <div style={{
                  width: 18, height: 18, border: '2.5px solid rgba(255,255,255,0.35)',
                  borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.7s linear infinite',
                  flexShrink: 0
                }} />
                  <span style={{ whiteSpace: 'nowrap' }}>กำลังเข้าสู่ระบบ...</span>
                </> :

              <>
                  <span style={{ flexShrink: 0, display: 'inline-flex' }}>{Icons.lock('#fff')}</span>
                  <span style={{ whiteSpace: 'nowrap' }}>เข้าสู่ระบบ</span>
                </>
              }
              {/* sweep */}
              <span style={{
                position: 'absolute', top: 0, left: '-100%', width: '60%', height: '100%',
                background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.25), transparent)',
                animation: 'btnSweep 2.6s ease-in-out infinite',
                animationPlayState: animPaused ? 'paused' : 'running',
                pointerEvents: 'none'
              }} />
            </button>
          </> :
          // Success state
          <div style={{ textAlign: 'center', padding: '14px 0 18px' }}>
              <div style={{
              width: 64, height: 64, borderRadius: '50%',
              background: `linear-gradient(135deg, #10b981, #34d399)`,
              margin: '0 auto 16px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 12px 32px rgba(16,185,129,0.4)'
            }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
                  <path d="M5 12 L 10 17 L 19 7" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div style={{ fontSize: 22, fontWeight: 800, color: p.text, marginBottom: 4 }}>เข้าสู่ระบบสำเร็จ</div>
              <div style={{ fontSize: 13, color: p.textMuted, marginBottom: 12 }}>กำลังพาคุณไปหน้า Dashboard...</div>
            </div>
          }
        </form>

        {/* Feature row */}
        <div style={{
          marginTop: 14, width: '100%', maxWidth: 380,
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8
        }}>
          {[
            { icon: '📄', label: 'จัดการเอกสาร', sub: 'อัตโนมัติด้วย AI' },
            { icon: '📊', label: 'วิเคราะห์ข้อมูล', sub: 'เชิงลึก' },
            { icon: '🛡️', label: 'ปลอดภัย', sub: 'ระดับองค์กร' },
            { icon: '☁️', label: 'ทำงานได้ทุกที่', sub: 'ทุกเวลา' }
          ].map((f, i) =>
            <div key={i} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              padding: '10px 4px', borderRadius: 12,
              background: p.featTint,
              border: `1px solid ${p.cardBorder}`
            }}>
              <div style={{ fontSize: 22, lineHeight: 1 }}>{f.icon}</div>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#fff', textAlign: 'center', lineHeight: 1.2 }}>{f.label}</div>
              <div style={{ fontSize: 10, color: p.featText, textAlign: 'center', lineHeight: 1.2 }}>{f.sub}</div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ marginTop: 14, textAlign: 'center' }}>
          <div style={{ fontSize: 11, color: p.footerText, marginBottom: 2 }}>
            © 2026 SC AccountPro · v1.0.0
          </div>
          <div style={{ fontSize: 10, color: p.footerSub, letterSpacing: 0.2 }}>
            Professional Accounting AI System for Thai Accountants
          </div>
        </div>
        <div style={{ height: 12 }} />
      </div>

      {/* ─── Forgot Password Modal ─────────────────────── */}
      {showForgot && (
      <div onClick={() => setShowForgot(false)} style={{
          position: 'fixed', inset: 0, zIndex: 9999,
          background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
          animation: 'fadeIn .15s ease'
        }}>
        <div onClick={(e) => e.stopPropagation()} style={{
            background: '#fff', borderRadius: 18, maxWidth: 440, width: '100%',
            padding: 28, boxShadow: '0 24px 80px rgba(0,0,0,0.4)',
            fontFamily: 'inherit'
          }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{
                width: 44, height: 44, borderRadius: 12,
                background: 'linear-gradient(135deg, #FEF3C7, #FDE68A)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 22
              }}>🔐</div>
            <div>
              <h3 style={{ fontSize: 17, fontWeight: 700, color: '#111827', margin: 0 }}>ลืมรหัสผ่าน?</h3>
              <p style={{ fontSize: 12, color: '#6B7280', margin: '2px 0 0' }}>วิธี reset รหัสผ่านของคุณ</p>
            </div>
          </div>

          <div style={{
              background: '#F0F9FF', border: '1.5px solid #BAE6FD',
              borderRadius: 12, padding: 14, marginBottom: 14
            }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#075985', marginBottom: 6 }}>
              📞 ติดต่อ Owner (ผู้ดูแลระบบ)
            </div>
            <div style={{ fontSize: 12.5, color: '#0C4A6E', lineHeight: 1.6 }}>
              แจ้ง Owner เพื่อ reset รหัสผ่านให้คุณ · Owner สามารถออกรหัสผ่านชั่วคราวให้ผ่านหน้า <b>"จัดการผู้ใช้ (User Admin)"</b> ได้
            </div>
          </div>

          <div style={{
              background: '#F9FAFB', borderRadius: 12, padding: 14, marginBottom: 14,
              fontSize: 12.5, color: '#374151', lineHeight: 1.7
            }}>
            <div style={{ fontWeight: 700, color: '#111827', marginBottom: 4 }}>ขั้นตอน:</div>
            <ol style={{ paddingLeft: 18, margin: 0 }}>
              <li>ติดต่อ Owner / ผู้ดูแลระบบ</li>
              <li>Owner reset password ในหน้า User Admin</li>
              <li>รับรหัสผ่านชั่วคราวจาก Owner</li>
              <li>Login → ระบบจะให้ตั้งรหัสผ่านใหม่ทันที</li>
            </ol>
          </div>

          <div style={{ fontSize: 11.5, color: '#6B7280', textAlign: 'center', marginBottom: 14 }}>
            🛡️ ระบบ reset ผ่าน Owner เท่านั้น เพื่อความปลอดภัยสูงสุด<br />
            (Email reset link จะมีในอัพเดตหน้า)
          </div>

          <button onClick={() => setShowForgot(false)} style={{
              width: '100%', height: 44, borderRadius: 12, border: 'none',
              background: 'linear-gradient(135deg, #2A4365, #2B6CB0)',
              color: '#fff', fontSize: 14, fontWeight: 700, cursor: 'pointer',
              fontFamily: 'inherit'
            }}>เข้าใจแล้ว</button>
        </div>
      </div>
      )}

    </div>
  );
}

// Export to window so App in login.html can render <LoginScreen>
Object.assign(window, { LoginScreen, PALETTES });
