// SG Canvas — renders the framed screenshot preview
// state: { bg, frame, padding, radius, shadow, tilt, aspect, image }

const PRESET_GRADIENTS = [
  { id: 'amber',   name: 'Amber',   css: 'linear-gradient(135deg, #f6c177 0%, #d97706 100%)' },
  { id: 'plum',    name: 'Plum',    css: 'linear-gradient(135deg, #a78bfa 0%, #6d28d9 100%)' },
  { id: 'forest',  name: 'Forest',  css: 'linear-gradient(135deg, #6ee7b7 0%, #047857 100%)' },
  { id: 'rose',    name: 'Rose',    css: 'linear-gradient(135deg, #fda4af 0%, #be123c 100%)' },
  { id: 'slate',   name: 'Slate',   css: 'linear-gradient(135deg, #cbd5e1 0%, #334155 100%)' },
  { id: 'noir',    name: 'Noir',    css: 'linear-gradient(135deg, #404040 0%, #0a0a0a 100%)' },
  { id: 'sand',    name: 'Sand',    css: 'linear-gradient(135deg, #fef3c7 0%, #b45309 100%)' },
  { id: 'ocean',   name: 'Ocean',   css: 'linear-gradient(135deg, #7dd3fc 0%, #0c4a6e 100%)' },
  { id: 'mint',    name: 'Mint',    css: 'linear-gradient(135deg, #a7f3d0 0%, #065f46 100%)' },
  { id: 'peach',   name: 'Peach',   css: 'linear-gradient(135deg, #fed7aa 0%, #c2410c 100%)' },
  { id: 'iris',    name: 'Iris',    css: 'linear-gradient(135deg, #c4b5fd 0%, #4c1d95 100%)' },
  { id: 'mesh-1',  name: 'Mesh',    css: 'radial-gradient(at 20% 20%, #fbbf24 0, transparent 50%), radial-gradient(at 80% 0%, #f97316 0, transparent 50%), radial-gradient(at 0% 100%, #be185d 0, transparent 50%), radial-gradient(at 100% 100%, #7c2d12 0, transparent 50%), #1c1917' },
];

const SOLID_COLORS = [
  '#0a0a0a', '#1c1917', '#292524', '#44403c',
  '#fafaf9', '#e7e5e4', '#fbbf24', '#dc2626',
  '#7c3aed', '#0ea5e9', '#10b981', '#ec4899',
];

const ASPECTS = [
  { id: '16:9',  label: '16:9',  w: 16, h: 9 },
  { id: '4:3',   label: '4:3',   w: 4,  h: 3 },
  { id: '1:1',   label: '1:1',   w: 1,  h: 1 },
  { id: '3:4',   label: '3:4',   w: 3,  h: 4 },
  { id: '9:16',  label: '9:16',  w: 9,  h: 16 },
  { id: 'auto',  label: 'auto',  w: null, h: null },
];

// Sample screenshot — a fake dashboard rendered as inline SVG so we don't depend on assets
const SampleScreenshot = ({ frame, theme = 'dark' }) => {
  const isDark = theme === 'dark';
  const c = isDark ? {
    bg: '#0c0a09', panel: '#1c1917', line: '#292524', text: '#fafaf9', muted: '#a8a29e', accent: '#f59e0b'
  } : {
    bg: '#fafaf9', panel: '#ffffff', line: '#e7e5e4', text: '#1c1917', muted: '#78716c', accent: '#d97706'
  };
  return (
    <svg viewBox="0 0 1280 800" preserveAspectRatio="xMidYMid slice" style={{ display: 'block', width: '100%', height: '100%' }}>
      <rect width="1280" height="800" fill={c.bg} />
      {/* sidebar */}
      <rect x="0" y="0" width="220" height="800" fill={c.panel} />
      <rect x="20" y="22" width="120" height="14" rx="3" fill={c.text} opacity="0.9" />
      <rect x="20" y="70" width="180" height="34" rx="6" fill={c.accent} opacity="0.18" />
      <rect x="36" y="83" width="80" height="8" rx="2" fill={c.accent} />
      {[120, 156, 192, 228, 264].map((y, i) => (
        <g key={i}>
          <rect x="20" y={y} width="14" height="14" rx="3" fill={c.muted} opacity="0.4" />
          <rect x="44" y={y + 4} width={90 + (i * 7) % 60} height="6" rx="2" fill={c.text} opacity="0.55" />
        </g>
      ))}
      <rect x="20" y="340" width="60" height="8" rx="2" fill={c.muted} opacity="0.6" />
      {[372, 400, 428, 456].map((y, i) => (
        <rect key={i} x="20" y={y} width={120 + (i * 11) % 50} height="6" rx="2" fill={c.text} opacity="0.4" />
      ))}
      {/* topbar */}
      <rect x="220" y="0" width="1060" height="64" fill={c.panel} />
      <line x1="220" y1="64" x2="1280" y2="64" stroke={c.line} />
      <rect x="248" y="22" width="180" height="20" rx="4" fill={c.text} opacity="0.85" />
      <rect x="1100" y="20" width="160" height="24" rx="6" fill={c.line} />
      <circle cx="1116" cy="32" r="5" fill={c.muted} opacity="0.6" />
      {/* metric cards */}
      {[0, 1, 2].map(i => (
        <g key={i} transform={`translate(${260 + i * 240}, 96)`}>
          <rect width="220" height="120" rx="10" fill={c.panel} stroke={c.line} />
          <rect x="20" y="20" width="60" height="8" rx="2" fill={c.muted} opacity="0.7" />
          <rect x="20" y="40" width={90 - i * 15} height="22" rx="3" fill={c.text} />
          <rect x="20" y="76" width="40" height="8" rx="2" fill={c.accent} opacity={i === 0 ? 1 : 0.5} />
          <rect x="65" y="76" width="60" height="8" rx="2" fill={c.muted} opacity="0.5" />
          <polyline points={`140,90 155,72 170,80 185,60 200,68`} fill="none" stroke={c.accent} strokeWidth="2" opacity={i === 0 ? 1 : 0.6} />
        </g>
      ))}
      {/* big chart */}
      <g transform="translate(260, 240)">
        <rect width="700" height="320" rx="10" fill={c.panel} stroke={c.line} />
        <rect x="22" y="22" width="120" height="10" rx="2" fill={c.text} opacity="0.85" />
        <rect x="22" y="40" width="80" height="8" rx="2" fill={c.muted} opacity="0.6" />
        {/* grid */}
        {[80, 130, 180, 230, 280].map(y => (
          <line key={y} x1="22" y1={y} x2="678" y2={y} stroke={c.line} />
        ))}
        {/* area */}
        <path d="M22 240 C 80 200, 140 220, 200 180 S 320 130, 380 150 S 500 100, 560 110 S 660 80, 678 95 L 678 280 L 22 280 Z"
              fill={c.accent} opacity="0.18" />
        <path d="M22 240 C 80 200, 140 220, 200 180 S 320 130, 380 150 S 500 100, 560 110 S 660 80, 678 95"
              fill="none" stroke={c.accent} strokeWidth="2.5" />
        {[
          [200, 180], [380, 150], [560, 110], [678, 95]
        ].map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="4" fill={c.panel} stroke={c.accent} strokeWidth="2" />
        ))}
      </g>
      {/* side card */}
      <g transform="translate(980, 240)">
        <rect width="280" height="320" rx="10" fill={c.panel} stroke={c.line} />
        <rect x="20" y="20" width="100" height="10" rx="2" fill={c.text} opacity="0.85" />
        {[60, 100, 140, 180, 220, 260].map((y, i) => (
          <g key={i}>
            <circle cx="32" cy={y + 8} r="10" fill={c.muted} opacity={0.3 + i * 0.05} />
            <rect x="52" y={y + 4} width={140 - i * 8} height="7" rx="2" fill={c.text} opacity="0.7" />
            <rect x="52" y={y + 16} width={90 + (i * 13) % 50} height="6" rx="2" fill={c.muted} opacity="0.5" />
            <rect x="240" y={y + 8} width="20" height="8" rx="2" fill={c.accent} opacity={i % 2 ? 0.4 : 0.8} />
          </g>
        ))}
      </g>
      {/* footer row */}
      <g transform="translate(260, 580)">
        <rect width="1000" height="180" rx="10" fill={c.panel} stroke={c.line} />
        <rect x="22" y="22" width="120" height="10" rx="2" fill={c.text} opacity="0.85" />
        {[0, 1, 2, 3, 4, 5, 6].map(i => (
          <rect key={i} x={24 + i * 138} y={60} width="120" height={60 + (i * 17) % 80} rx="4"
            fill={c.accent} opacity={0.3 + (i % 4) * 0.18} />
        ))}
      </g>
    </svg>
  );
};

const BrowserChrome = ({ children, url = 'screengod.app/preview', theme = 'light' }) => {
  const isDark = theme === 'dark';
  return (
    <div style={{
      background: isDark ? '#1c1917' : '#f5f5f4',
      borderBottom: isDark ? '1px solid #292524' : '1px solid #e7e5e4',
      display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px',
      fontSize: 12, color: isDark ? '#a8a29e' : '#78716c'
    }}>
      <div style={{ display: 'flex', gap: 6 }}>
        {['#ff5f57', '#febc2e', '#28c840'].map(c => (
          <div key={c} style={{ width: 11, height: 11, borderRadius: '50%', background: c }} />
        ))}
      </div>
      <div style={{
        flex: 1, background: isDark ? '#0c0a09' : '#fff',
        border: isDark ? '1px solid #292524' : '1px solid #e7e5e4',
        borderRadius: 6, padding: '5px 10px', fontFamily: 'Geist Mono, monospace',
        fontSize: 11, letterSpacing: -0.1, textAlign: 'center'
      }}>{url}</div>
      <div style={{ width: 40 }} />
    </div>
  );
};

const DeviceChrome = ({ children }) => (
  <div style={{
    background: '#0a0a0a', padding: '14px 8px 6px',
    display: 'flex', justifyContent: 'center', alignItems: 'center',
    fontSize: 11, fontFamily: 'Geist Mono, monospace', color: '#a8a29e'
  }}>
    <span style={{ width: 100, height: 22, background: '#000', borderRadius: 14 }} />
  </div>
);

// Main canvas
function SGCanvas({ s, onUpdate, fullscreen = false, registerStageRef, zoom = 100, activeTool, setActiveTool }) {
  const stageRef = React.useRef(null);
  const [drawing, setDrawing] = React.useState(null);

  React.useEffect(() => {
    if (registerStageRef) registerStageRef(stageRef);
  }, []);

  const bgStyle = (() => {
    if (s.bg.type === 'gradient') {
      const g = PRESET_GRADIENTS.find(x => x.id === s.bg.value) || PRESET_GRADIENTS[0];
      return { background: g.css };
    }
    if (s.bg.type === 'solid') return { background: s.bg.value };
    if (s.bg.type === 'pattern') {
      return {
        background: '#1c1917',
        backgroundImage: `radial-gradient(circle at 1px 1px, rgba(245,158,11,0.18) 1px, transparent 0)`,
        backgroundSize: '24px 24px'
      };
    }
    return { background: '#0a0a0a' };
  })();

  const aspect = ASPECTS.find(a => a.id === s.aspect) || ASPECTS[0];
  // The OUTPUT aspect is the stage; the screenshot itself stays 16:9 inside the padding.
  const stageStyle = aspect.w ? { aspectRatio: `${aspect.w} / ${aspect.h}` } : {};

  const innerPad = `${s.padding}px`;
  const radius = `${s.radius}px`;

  const shadowMap = {
    none: 'none',
    soft: '0 20px 50px -20px rgba(0,0,0,0.5)',
    medium: '0 30px 60px -15px rgba(0,0,0,0.6), 0 12px 24px -8px rgba(0,0,0,0.3)',
    hard: '0 50px 100px -20px rgba(0,0,0,0.85), 0 30px 60px -30px rgba(0,0,0,0.6)',
    glow: `0 0 80px -10px ${s.bg.type === 'gradient' ? 'rgba(245,158,11,0.4)' : 'rgba(255,255,255,0.15)'}, 0 30px 60px -15px rgba(0,0,0,0.5)`,
  };

  const tiltTransform = s.tilt > 0
    ? `perspective(2200px) rotateY(${s.tilt}deg) rotateX(${s.tilt * 0.4}deg)`
    : 'none';

  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      overflow: 'hidden',
      background: 'var(--bg-0)',
      backgroundImage: `
        linear-gradient(45deg, oklch(0.19 0.012 84) 25%, transparent 25%),
        linear-gradient(-45deg, oklch(0.19 0.012 84) 25%, transparent 25%),
        linear-gradient(45deg, transparent 75%, oklch(0.19 0.012 84) 75%),
        linear-gradient(-45deg, transparent 75%, oklch(0.19 0.012 84) 75%)`,
      backgroundSize: '20px 20px',
      backgroundPosition: '0 0, 0 10px, 10px -10px, -10px 0px',
    }}>
      <div style={{ transform: `scale(${zoom / 100})`, transition: 'transform 0.2s', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div ref={stageRef} style={{
        width: '85%', maxWidth: fullscreen ? 1400 : 1000,
        ...stageStyle,
        ...bgStyle,
        borderRadius: fullscreen ? 0 : 8,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: innerPad, position: 'relative',
        boxShadow: '0 1px 0 rgba(255,255,255,0.06) inset',
        transition: 'all 0.25s cubic-bezier(.2,.7,.2,1)',
      }}>
        {/* watermark */}
        {s.watermark && (
          <div style={{
            position: 'absolute', bottom: 12, right: 14,
            fontFamily: 'Geist Mono, monospace', fontSize: 10,
            letterSpacing: 1.5, textTransform: 'uppercase',
            color: 'rgba(255,255,255,0.6)', mixBlendMode: 'difference',
            pointerEvents: 'none'
          }}>
            screengod / {s.watermarkText || '@you'}
          </div>
        )}
        <div style={{
          width: '100%', height: '100%',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          transform: tiltTransform,
          transformOrigin: 'center',
          transition: 'transform 0.3s cubic-bezier(.2,.7,.2,1)',
          minHeight: 0, minWidth: 0,
        }}>
          <div style={{
            background: '#000',
            borderRadius: radius,
            overflow: 'hidden',
            boxShadow: shadowMap[s.shadow],
            display: 'flex', flexDirection: 'column',
            border: s.border ? '1px solid rgba(255,255,255,0.12)' : 'none',
            maxWidth: '100%',
            maxHeight: '100%',
          }}>
            {s.frame === 'browser' && <BrowserChrome url={s.url} theme={s.frameTheme} />}
            {s.frame === 'window' && <BrowserChrome url="" theme={s.frameTheme} />}
            {s.frame === 'device' && <DeviceChrome />}
            <div 
              style={{ position: 'relative', background: '#000', display: 'flex', justifyContent: 'center', alignItems: 'center', minWidth: 0, minHeight: 0, flex: 1, overflow: 'hidden' }}
              onPointerDown={e => {
                if (!activeTool || ['cursor', 'image', 'sparkle'].includes(activeTool)) return;
                const r = e.currentTarget.getBoundingClientRect();
                const x = ((e.clientX - r.left) / r.width) * 100;
                const y = ((e.clientY - r.top) / r.height) * 100;
                if (activeTool === 'text') {
                  const txt = prompt('Текст аннотации:');
                  if (txt) {
                    onUpdate(p => ({ ...p, annotations: [...(p.annotations || []), { id: Date.now(), type: 'label', x, y, text: txt }] }));
                  }
                  setActiveTool('cursor');
                  return;
                }
                setDrawing({ type: activeTool, x1: x, y1: y, x2: x, y2: y });
                e.currentTarget.setPointerCapture(e.pointerId);
              }}
              onPointerMove={e => {
                if (!drawing) return;
                const r = e.currentTarget.getBoundingClientRect();
                const x = Math.max(0, Math.min(100, ((e.clientX - r.left) / r.width) * 100));
                const y = Math.max(0, Math.min(100, ((e.clientY - r.top) / r.height) * 100));
                setDrawing({ ...drawing, x2: x, y2: y });
              }}
              onPointerUp={e => {
                if (!drawing) return;
                e.currentTarget.releasePointerCapture(e.pointerId);
                if (Math.abs(drawing.x1 - drawing.x2) > 1 || Math.abs(drawing.y1 - drawing.y2) > 1) {
                  onUpdate(p => ({ ...p, annotations: [...(p.annotations || []), { id: Date.now(), ...drawing }] }));
                }
                setDrawing(null);
                setActiveTool('cursor');
              }}
            >
              {s.image ? (
                <img src={s.image} style={{ 
                  display: 'block', maxWidth: '100%', maxHeight: '100%', width: 'auto', height: 'auto', objectFit: 'contain', pointerEvents: 'none',
                  filter: s.enhance ? 'contrast(1.15) saturate(1.2) brightness(1.05)' : 'none',
                  transition: 'filter 0.3s'
                }} />
              ) : (
                <div style={{ width: 800, maxWidth: '100%', aspectRatio: '16 / 10', pointerEvents: 'none' }}>
                  <SampleScreenshot frame={s.frame} theme={s.frameTheme} />
                </div>
              )}
              {/* annotations layer */}
              {s.annotations && s.annotations.map(a => (
                <Annotation key={a.id} a={a} />
              ))}
              {drawing && <Annotation a={{ id: 'preview', ...drawing }} />}
            </div>
          </div>
          {s.caption && (
            <div style={{
              marginTop: 16, textAlign: 'center',
              color: 'rgba(255,255,255,0.92)',
              fontWeight: 500, fontSize: 16,
              textShadow: '0 1px 8px rgba(0,0,0,0.3)'
            }}>{s.caption}</div>
          )}
        </div>
      </div>
      </div>
    </div>
  );
}

const Annotation = ({ a }) => {
  if (a.type === 'arrow') {
    return (
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', zIndex: 10, overflow: 'visible' }}>
        <defs>
          <marker id={`m-${a.id}`} viewBox="0 0 10 10" refX="7" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
            <path d="M0 1 L8 5 L0 9 z" fill="var(--accent, #f59e0b)" />
          </marker>
        </defs>
        <line x1={`${a.x1}%`} y1={`${a.y1}%`} x2={`${a.x2}%`} y2={`${a.y2}%`}
              stroke="var(--accent, #f59e0b)" strokeWidth="4" fill="none" markerEnd={`url(#m-${a.id})`} strokeLinecap="round" />
      </svg>
    );
  }
  if (a.type === 'blur') {
    const left = Math.min(a.x1, a.x2);
    const top = Math.min(a.y1, a.y2);
    const width = Math.abs(a.x1 - a.x2);
    const height = Math.abs(a.y1 - a.y2);
    return (
      <div style={{
        position: 'absolute', left: `${left}%`, top: `${top}%`, width: `${width}%`, height: `${height}%`,
        backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
        borderRadius: 6, zIndex: 5, pointerEvents: 'none',
        boxShadow: '0 0 0 1px rgba(255,255,255,0.1) inset'
      }} />
    );
  }
  if (a.type === 'label') {
    return (
      <div style={{
        position: 'absolute', left: `${a.x}%`, top: `${a.y}%`,
        background: 'var(--accent, #f59e0b)', color: '#1c1917', padding: '6px 14px',
        borderRadius: 999, fontSize: 13, fontWeight: 600,
        boxShadow: '0 4px 20px rgba(0,0,0,0.4)',
        transform: 'translate(-50%, -50%)', zIndex: 15, pointerEvents: 'none'
      }}>{a.text}</div>
    );
  }
  return null;
};

Object.assign(window, { SGCanvas, PRESET_GRADIENTS, SOLID_COLORS, ASPECTS });
