/* global React */
const { useEffect: useEffectDash, useState: useStateDash, useRef: useRefDash } = React;

/* ============================================
   DASHBOARD MOCKUP — animated SaaS interface
   ============================================ */
function DashboardMockup() {
  const [activeTab, setActiveTab] = useStateDash(0);
  const [pulse, setPulse] = useStateDash(0);

  useEffectDash(() => {
    const id = setInterval(() => setPulse(p => p + 1), 2400);
    return () => clearInterval(id);
  }, []);

  // Auto-cycle tabs
  useEffectDash(() => {
    const id = setInterval(() => setActiveTab(t => (t + 1) % 3), 5500);
    return () => clearInterval(id);
  }, []);

  return (
    <div style={{
      position: 'relative',
      width: '100%',
      maxWidth: 720,
      aspectRatio: '4 / 3',
      perspective: 1800,
    }}>
      {/* Glow underneath */}
      <div style={{
        position: 'absolute', inset: '-40px -60px -40px -60px',
        background: 'radial-gradient(ellipse at center, rgba(47,133,90,0.18), transparent 65%)',
        filter: 'blur(40px)', pointerEvents: 'none',
      }} />

      {/* Main dashboard frame */}
      <div style={{
        position: 'relative',
        width: '100%', height: '100%',
        background: 'linear-gradient(160deg, #101713 0%, #0E1512 100%)',
        borderRadius: 18,
        boxShadow: `
          0 1px 0 rgba(255,255,255,0.04) inset,
          0 60px 120px -30px rgba(0,0,0,0.7),
          0 30px 60px -20px rgba(100,116,107,0.3),
          0 0 0 1px rgba(47,133,90,0.18)
        `,
        overflow: 'hidden',
        transform: 'rotateY(-6deg) rotateX(3deg)',
        transformStyle: 'preserve-3d',
      }}>
        {/* Gold edge highlight */}
        <div style={{
          position: 'absolute', inset: 0, borderRadius: 18, pointerEvents: 'none',
          background: 'linear-gradient(135deg, rgba(47,133,90,0.25), transparent 30%, transparent 70%, rgba(47,133,90,0.1))',
          padding: 1,
          WebkitMask: 'linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)',
          WebkitMaskComposite: 'xor',
          maskComposite: 'exclude',
        }} />

        {/* Title bar */}
        <div style={{
          padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
          borderBottom: '1px solid rgba(244,247,245,0.06)',
          background: 'rgba(10,15,13,0.5)',
        }}>
          <div style={{ display: 'flex', gap: 6 }}>
            <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#3a3a3a' }} />
            <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#3a3a3a' }} />
            <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#3a3a3a' }} />
          </div>
          <div style={{
            flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center',
            gap: 8, color: 'var(--vp-cream-faint)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.05em',
          }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#2F855A', boxShadow: '0 0 8px #2F855A' }} />
            app.vivopartner.ai/dashboard
          </div>
          <div style={{ width: 27 }} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr', height: 'calc(100% - 32px)' }}>
          {/* Sidebar */}
          <div style={{
            background: 'rgba(10,15,13,0.4)',
            borderRight: '1px solid rgba(244,247,245,0.05)',
            padding: '14px 10px',
            display: 'flex', flexDirection: 'column', gap: 4,
          }}>
            <div className="mono" style={{
              fontSize: 8, color: 'var(--vp-cream-faint)', letterSpacing: '0.2em',
              padding: '4px 8px', textTransform: 'uppercase', marginBottom: 4,
            }}>
              Workspace
            </div>
            {[
              { i: '◉', l: 'Devis & Factures', active: 0 },
              { i: '◇', l: 'CRM & Clients', active: 1 },
              { i: '◈', l: 'Suivi Chantier', active: 2 },
              { i: '◌', l: 'Relances impayés', active: -1 },
              { i: '◍', l: 'Planning équipe', active: -1 },
              { i: '◎', l: 'Comptabilité', active: -1 },
            ].map((item, idx) => (
              <button key={idx}
                onClick={() => item.active >= 0 && setActiveTab(item.active)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 8,
                  padding: '7px 9px', borderRadius: 7,
                  background: activeTab === item.active ? 'linear-gradient(90deg, rgba(47,133,90,0.14), rgba(47,133,90,0.04))' : 'transparent',
                  border: 'none', cursor: 'pointer',
                  color: activeTab === item.active ? 'var(--vp-gold-light)' : 'var(--vp-cream-dim)',
                  fontSize: 11, fontFamily: 'var(--font-body)', fontWeight: 450,
                  textAlign: 'left', transition: 'all 0.3s',
                  boxShadow: activeTab === item.active ? 'inset 1px 0 0 var(--vp-gold)' : 'none',
                }}>
                <span style={{ fontSize: 10 }}>{item.i}</span>
                {item.l}
              </button>
            ))}
            <div style={{ flex: 1 }} />
            <div style={{
              padding: 10, borderRadius: 8,
              background: 'linear-gradient(135deg, rgba(100,116,107,0.25), rgba(18,61,50,0.25))',
              border: '1px solid rgba(47,133,90,0.18)',
            }}>
              <div className="mono" style={{ fontSize: 8, color: 'var(--vp-gold)', letterSpacing: '0.15em', marginBottom: 4 }}>
                IA ACTIVE
              </div>
              <div style={{ fontSize: 10, color: 'var(--vp-cream)', lineHeight: 1.3, fontWeight: 500 }}>
                14 workflows en exécution
              </div>
            </div>
          </div>

          {/* Main content area */}
          <div style={{ padding: '14px 18px', overflow: 'hidden', position: 'relative' }}>
            <TabContent activeTab={activeTab} pulse={pulse} />
          </div>
        </div>
      </div>

      {/* Floating callouts */}
      <div style={{
        position: 'absolute', top: '8%', right: '-8%',
        animation: 'vp-orb-float 8s ease-in-out infinite',
      }} className="dash-callout">
        <FloatingCard
          icon="↗"
          eyebrow="GAIN MOYEN"
          value="+10h"
          subtitle="par semaine"
        />
      </div>

      <div style={{
        position: 'absolute', bottom: '12%', left: '-10%',
        animation: 'vp-orb-float 10s ease-in-out infinite reverse',
      }} className="dash-callout">
        <FloatingCard
          icon="◎"
          eyebrow="TAUX CONVERSION"
          value="3.4×"
          subtitle="vs avant"
          accent="green"
        />
      </div>

      <style>{`
        @media (max-width: 900px) {
          .dash-callout { display: none !important; }
        }
      `}</style>
    </div>
  );
}

/* ============================================
   TAB CONTENT — three distinct views
   ============================================ */
function TabContent({ activeTab, pulse }) {
  const headers = [
    { eyebrow: 'FACTURATION · 30 JOURS', title: 'Devis & Factures', badge: 'LIVE · +24%' },
    { eyebrow: 'CLIENTS · TEMPS RÉEL', title: 'CRM & Clients', badge: '348 ACTIFS · +42%' },
    { eyebrow: 'CHANTIERS EN COURS · TEMPS RÉEL', title: 'Suivi Chantier', badge: '14 ACTIFS · 99.8%' },
  ];
  const h = headers[activeTab];

  return (
    <div key={activeTab} style={{ animation: 'vp-fade-up 0.5s ease-out' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
        <div>
          <div className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)', letterSpacing: '0.2em', marginBottom: 4 }}>
            {h.eyebrow}
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 400, letterSpacing: '-0.02em', color: 'var(--vp-cream)' }}>
            {h.title}
          </div>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6, padding: '5px 10px',
          background: 'rgba(47,133,90,0.2)', border: '1px solid rgba(47,133,90,0.5)',
          borderRadius: 999, fontSize: 9, color: '#7BD4A8', fontFamily: 'var(--font-mono)',
        }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#7BD4A8', boxShadow: '0 0 6px #7BD4A8' }} />
          {h.badge}
        </div>
      </div>

      {activeTab === 0 && <OverviewView pulse={pulse} />}
      {activeTab === 1 && <PipelineView />}
      {activeTab === 2 && <AutomationsView />}
    </div>
  );
}

function OverviewView({ pulse }) {
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 12 }}>
        {[
          { l: 'Devis envoyés', v: '47', d: '+18%', c: 'var(--vp-gold-light)' },
          { l: 'Factures payées', v: '€89.4k', d: '+31%', c: '#7BD4A8' },
          { l: 'Délai moyen', v: '8j', d: '−42%', c: 'var(--vp-gold-light)' },
        ].map((k, i) => (
          <div key={i} style={{
            padding: '10px 11px', borderRadius: 9,
            background: 'rgba(244,247,245,0.025)', border: '1px solid rgba(244,247,245,0.05)',
          }}>
            <div className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)', letterSpacing: '0.12em', marginBottom: 4 }}>
              {k.l.toUpperCase()}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 500, color: k.c, lineHeight: 1, letterSpacing: '-0.02em' }}>
              {k.v}
            </div>
            <div style={{ fontSize: 9, color: '#7BD4A8', marginTop: 3, fontFamily: 'var(--font-mono)' }}>↑ {k.d}</div>
          </div>
        ))}
      </div>

      <div style={{
        position: 'relative', height: 130, padding: '10px 12px',
        background: 'rgba(244,247,245,0.02)', border: '1px solid rgba(244,247,245,0.05)',
        borderRadius: 10, marginBottom: 10,
      }}>
        <ChartArea pulse={pulse} variant={0} />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
        {[
          { i: '✦', t: 'Devis #2847 envoyé · Maison Lambert — €12 400', c: 'var(--vp-gold-light)', time: '2 min' },
          { i: '◆', t: 'Facture #1923 payée · Acme Corp — €8 900', c: '#7BD4A8', time: '5 min' },
          { i: '◇', t: 'Relance auto envoyée · 3 factures en retard', c: 'var(--vp-cream-dim)', time: '12 min' },
        ].map((row, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 9, padding: '6px 10px', borderRadius: 6,
            background: i === 0 ? 'rgba(47,133,90,0.06)' : 'transparent', fontSize: 10,
          }}>
            <span style={{ color: row.c, fontSize: 10 }}>{row.i}</span>
            <span style={{ flex: 1, color: 'var(--vp-cream-dim)' }}>{row.t}</span>
            <span className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)' }}>il y a {row.time}</span>
          </div>
        ))}
      </div>
    </>
  );
}

function PipelineView() {
  // CRM client funnel
  const stages = [
    { l: 'Prospects', n: 142, c: '#7BD4A8' },
    { l: 'Devis envoyés', n: 87, c: 'var(--vp-gold-light)' },
    { l: 'Clients signés', n: 23, c: 'var(--vp-bordeaux-glow)' },
  ];

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 10 }}>
        {stages.map((s, i) => (
          <div key={i} style={{
            padding: '10px 11px', borderRadius: 9,
            background: 'rgba(244,247,245,0.025)', border: '1px solid rgba(244,247,245,0.05)',
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', top: 0, left: 0, right: 0, height: 2,
              background: `linear-gradient(90deg, ${s.c}, transparent)`,
            }} />
            <div className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)', letterSpacing: '0.12em', marginBottom: 4 }}>
              {s.l.toUpperCase()}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 500, color: s.c, lineHeight: 1, letterSpacing: '-0.02em' }}>
              {s.n}
            </div>
            <div style={{ fontSize: 9, color: 'var(--vp-cream-dim)', marginTop: 3 }}>contacts actifs</div>
          </div>
        ))}
      </div>

      <div style={{
        height: 130, padding: '10px 12px', marginBottom: 10,
        background: 'rgba(244,247,245,0.02)', border: '1px solid rgba(244,247,245,0.05)',
        borderRadius: 10, display: 'flex', alignItems: 'flex-end', gap: 6,
      }}>
        {[100, 88, 72, 58, 42, 28, 18, 12].map((h, i) => (
          <div key={i} style={{
            flex: 1, height: `${h}%`,
            background: `linear-gradient(180deg, var(--vp-gold-light), var(--vp-gold-dark))`,
            borderRadius: '3px 3px 1px 1px',
            transformOrigin: 'bottom',
            animation: `vp-bar-grow 0.8s ease-out ${i * 0.06}s both`,
            opacity: 0.4 + (h / 100) * 0.6,
          }} />
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
        {[
          { i: '◆', t: 'Acme Corp · devis accepté — passage en client', c: '#7BD4A8', time: '1 min' },
          { i: '✦', t: 'Maison Lambert · RDV planifié jeudi 14h', c: 'var(--vp-gold-light)', time: '8 min' },
          { i: '↗', t: 'Helvex Studio · relance commerciale auto', c: 'var(--vp-bordeaux-glow)', time: '21 min' },
        ].map((row, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 9, padding: '6px 10px', borderRadius: 6,
            background: i === 0 ? 'rgba(47,133,90,0.06)' : 'transparent', fontSize: 10,
          }}>
            <span style={{ color: row.c, fontSize: 10 }}>{row.i}</span>
            <span style={{ flex: 1, color: 'var(--vp-cream-dim)' }}>{row.t}</span>
            <span className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)' }}>il y a {row.time}</span>
          </div>
        ))}
      </div>
    </>
  );
}

function AutomationsView() {
  const flows = [
    { name: 'Chantier · Résidence Lambert', runs: 78, status: 'running', success: 78 },
    { name: 'Chantier · Bureaux Acme', runs: 92, status: 'running', success: 92 },
    { name: 'Chantier · Loft Helvex', runs: 45, status: 'running', success: 45 },
    { name: 'Chantier · Villa Crestline', runs: 12, status: 'idle', success: 12 },
  ];

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 10 }}>
        {[
          { l: 'Chantiers actifs', v: '14', d: '+3', c: 'var(--vp-gold-light)' },
          { l: 'Heures suivies', v: '2.4k', d: '+18%', c: '#7BD4A8' },
          { l: 'Marge moyenne', v: '32%', d: '+4pts', c: 'var(--vp-gold-light)' },
        ].map((k, i) => (
          <div key={i} style={{
            padding: '10px 11px', borderRadius: 9,
            background: 'rgba(244,247,245,0.025)', border: '1px solid rgba(244,247,245,0.05)',
          }}>
            <div className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)', letterSpacing: '0.12em', marginBottom: 4 }}>
              {k.l.toUpperCase()}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 500, color: k.c, lineHeight: 1, letterSpacing: '-0.02em' }}>
              {k.v}
            </div>
            <div style={{ fontSize: 9, color: '#7BD4A8', marginTop: 3, fontFamily: 'var(--font-mono)' }}>↑ {k.d}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
        {flows.map((f, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '8px 11px',
            background: 'rgba(244,247,245,0.025)', border: '1px solid rgba(244,247,245,0.05)',
            borderRadius: 8,
          }}>
            <span style={{
              width: 7, height: 7, borderRadius: '50%',
              background: f.status === 'running' ? '#7BD4A8' : 'var(--vp-cream-faint)',
              boxShadow: f.status === 'running' ? '0 0 6px #7BD4A8' : 'none',
              animation: f.status === 'running' ? 'vp-pulse-ring 1.8s ease-out infinite' : 'none',
              flexShrink: 0,
            }} />
            <span style={{ flex: 1, fontSize: 11, color: 'var(--vp-cream)' }}>{f.name}</span>
            <span className="mono" style={{ fontSize: 9, color: 'var(--vp-cream-dim)' }}>
              {f.success}% avancé
            </span>
            <span className="mono" style={{
              fontSize: 9,
              color: f.success > 70 ? '#7BD4A8' : 'var(--vp-gold-light)',
              minWidth: 36, textAlign: 'right',
            }}>
              {f.status === 'running' ? 'en cours' : 'attente'}
            </span>
          </div>
        ))}
      </div>
    </>
  );
}

function FloatingCard({ icon, eyebrow, value, subtitle, accent = 'gold' }) {
  const isGreen = accent === 'green';
  return (
    <div style={{
      padding: '12px 16px',
      background: 'rgba(14, 12, 18, 0.92)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      borderRadius: 14,
      border: `1px solid ${isGreen ? 'rgba(47,133,90,0.5)' : 'rgba(47,133,90,0.3)'}`,
      boxShadow: '0 20px 40px -10px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04) inset',
      display: 'flex', alignItems: 'center', gap: 12,
      minWidth: 170,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: isGreen ? 'linear-gradient(135deg, #2F855A, #0B2B22)' : 'var(--grad-gold)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 18, color: isGreen ? 'var(--vp-gold-light)' : '#07140E',
        boxShadow: isGreen ? '0 4px 12px -2px rgba(47,133,90,0.6)' : '0 4px 12px -2px rgba(47,133,90,0.5)',
      }}>{icon}</div>
      <div>
        <div className="mono" style={{ fontSize: 8, color: 'var(--vp-cream-faint)', letterSpacing: '0.15em', marginBottom: 2 }}>
          {eyebrow}
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, color: 'var(--vp-cream)', letterSpacing: '-0.02em' }}>
            {value}
          </span>
          <span style={{ fontSize: 10, color: 'var(--vp-cream-dim)' }}>{subtitle}</span>
        </div>
      </div>
    </div>
  );
}

/* ============================================
   CHART AREA — animated SVG line + bars
   ============================================ */
function ChartArea({ pulse, variant }) {
  // Three different chart shapes
  const paths = [
    'M 0 80 Q 40 70 70 60 T 140 35 T 210 30 T 280 18 T 350 8',
    'M 0 70 Q 40 65 70 50 T 140 55 T 210 30 T 280 25 T 350 12',
    'M 0 75 Q 40 60 70 55 T 140 40 T 210 45 T 280 22 T 350 14',
  ];
  const path = paths[variant % 3];

  // Generate area path
  const areaPath = `${path} L 350 110 L 0 110 Z`;

  return (
    <svg viewBox="0 0 350 110" width="100%" height="100%" preserveAspectRatio="none" style={{ overflow: 'visible' }}>
      <defs>
        <linearGradient id="goldFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(47,133,90,0.45)" />
          <stop offset="100%" stopColor="rgba(47,133,90,0)" />
        </linearGradient>
        <linearGradient id="goldStroke" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#1E5A3C" />
          <stop offset="50%" stopColor="#4FB07A" />
          <stop offset="100%" stopColor="#2F855A" />
        </linearGradient>
      </defs>

      {/* Grid lines */}
      {[0, 25, 50, 75, 100].map(y => (
        <line key={y} x1="0" y1={y} x2="350" y2={y} stroke="rgba(244,247,245,0.04)" strokeWidth="0.5" strokeDasharray="2 4" />
      ))}

      {/* Area fill */}
      <path
        key={`area-${pulse}-${variant}`}
        d={areaPath}
        fill="url(#goldFill)"
        style={{ animation: 'vp-fade-up 1.4s ease-out' }}
      />

      {/* Line */}
      <path
        key={`line-${pulse}-${variant}`}
        d={path}
        fill="none"
        stroke="url(#goldStroke)"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeDasharray="500"
        strokeDashoffset="500"
        style={{ animation: 'vp-line-trace 1.6s ease-out forwards' }}
      />

      {/* End point */}
      <g transform="translate(350, 8)" style={{ animation: 'vp-fade-up 0.5s 1.2s both' }}>
        <circle r="8" fill="rgba(47,133,90,0.25)" style={{ animation: 'vp-pulse-ring 1.8s ease-out infinite' }} />
        <circle r="3.5" fill="#4FB07A" />
        <circle r="1.5" fill="#fff" />
      </g>
    </svg>
  );
}

window.DashboardMockup = DashboardMockup;
