// modals.jsx — Shade detail modal, Export modal, UI preview
const CUm = window.ColorUtil;

function ShadeDetailModal({ shade, idx, total, baseHex, onClose, onPrev, onNext, onCopy, copiedTag }) {
  React.useEffect(() => {
    const onKey = e => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onPrev();
      if (e.key === 'ArrowRight') onNext();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose, onPrev, onNext]);

  const hsl = CUm.rgbToHsl(shade.rgb);
  const oklch = CUm.rgbToOklch(shade.rgb);
  const cmyk = CUm.rgbToCmyk(shade.rgb);
  const named = CUm.closestNamed(shade.hex);

  const cWhite = CUm.contrastRatio(shade.rgb, { r: 255, g: 255, b: 255 });
  const cBlack = CUm.contrastRatio(shade.rgb, { r: 0, g: 0, b: 0 });

  const fields = [
    { k: 'HEX',   v: shade.hex,          copy: shade.hex },
    { k: 'RGB',   v: fmtRgbC(shade.rgb), copy: fmtRgbC(shade.rgb) },
    { k: 'HSL',   v: fmtHslC(hsl),       copy: fmtHslC(hsl) },
    { k: 'OKLCH', v: fmtOklchC(oklch),   copy: fmtOklchC(oklch) },
    { k: 'CMYK',  v: fmtCmykC(cmyk),     copy: fmtCmykC(cmyk) },
  ];

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal detail" onClick={e => e.stopPropagation()}>
        <div className="detail-swatch" style={{ background: shade.hex }}>
          <button className="modal-nav left" onClick={onPrev} aria-label="Previous"><ChevronL /></button>
          <button className="modal-nav right" onClick={onNext} aria-label="Next"><ChevronR /></button>
          <button className="modal-close" onClick={onClose} aria-label="Close"><CloseIcon /></button>
          <div className="detail-swatch-label" style={{ color: cBlack > cWhite ? '#111' : '#fff' }}>
            <div className="detail-idx">Stop {idx + 1} of {total}</div>
            <div className="detail-hex">{shade.hex}</div>
            <div className="detail-named">≈ {named.name}</div>
          </div>
        </div>
        <div className="detail-body">
          <div className="detail-section">
            <div className="detail-section-label">Formats</div>
            <div className="detail-fields">
              {fields.map(f => {
                const tag = `dm-${f.k}`;
                return (
                  <button key={f.k} className="detail-field" onClick={() => onCopy(f.copy, tag)}>
                    <span className="df-k">{f.k}</span>
                    <span className="df-v">{f.v}</span>
                    <span className="df-ico">
                      {copiedTag === tag ? <CheckIcon /> : <CopyIcon />}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="detail-section">
            <div className="detail-section-label">Accessibility</div>
            <div className="contrast-grid">
              <ContrastCell bg={shade.hex} fg="#FFFFFF" ratio={cWhite} label="on White" />
              <ContrastCell bg={shade.hex} fg="#000000" ratio={cBlack} label="on Black" />
            </div>
          </div>

          <div className="detail-section">
            <div className="detail-section-label">Nearest named</div>
            <div className="named-row">
              <span className="named-sw" style={{ background: named.hex }} />
              <span className="named-name">{named.name}</span>
              <span className="named-hex">{named.hex}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ContrastCell({ bg, fg, ratio, label }) {
  const grade =
    ratio >= 7 ? 'AAA' :
    ratio >= 4.5 ? 'AA' :
    ratio >= 3 ? 'AA Large' : 'Fail';
  const tone = ratio >= 4.5 ? 'pass' : ratio >= 3 ? 'warn' : 'fail';
  return (
    <div className="contrast-cell">
      <div className="contrast-sample" style={{ background: bg, color: fg }}>
        <span style={{ fontSize: 22, fontWeight: 600 }}>Aa</span>
        <span style={{ fontSize: 11, opacity: .85 }}>The quick brown fox</span>
      </div>
      <div className="contrast-meta">
        <div className="contrast-label">{label}</div>
        <div className="contrast-ratio">
          <span className="cr-val">{ratio.toFixed(2)}</span>
          <span className={`cr-grade ${tone}`}>{grade}</span>
        </div>
      </div>
    </div>
  );
}

// ─── Export modal ────────────────────────────────────────────────────────────
function ExportModal({ shades, baseHex, onClose, onCopy, copiedTag }) {
  const [tab, setTab] = React.useState('css');
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const name = 'brand';
  // use tailwind-ish scale with N stops
  const scale = scaleFromCount(shades.length);

  const cssText = [
    ':root {',
    ...shades.map((s, i) => `  --${name}-${scale[i]}: ${s.hex};`),
    '}',
  ].join('\n');

  const tailwindText = [
    '// tailwind.config.js',
    'module.exports = {',
    '  theme: {',
    '    extend: {',
    '      colors: {',
    `        ${name}: {`,
    ...shades.map((s, i) => `          ${scale[i]}: '${s.hex}',`),
    '        },',
    '      },',
    '    },',
    '  },',
    '};',
  ].join('\n');

  const jsonText = JSON.stringify(
    {
      name,
      base: baseHex,
      scale: Object.fromEntries(shades.map((s, i) => [scale[i], s.hex])),
    },
    null, 2
  );

  const scssText = shades.map((s, i) => `$${name}-${scale[i]}: ${s.hex};`).join('\n');

  const tabs = [
    { id: 'css', label: 'CSS variables', text: cssText, lang: 'css' },
    { id: 'tailwind', label: 'Tailwind', text: tailwindText, lang: 'js' },
    { id: 'scss', label: 'SCSS', text: scssText, lang: 'scss' },
    { id: 'json', label: 'JSON', text: jsonText, lang: 'json' },
  ];
  const active = tabs.find(t => t.id === tab);

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal export" onClick={e => e.stopPropagation()}>
        <div className="export-head">
          <div>
            <h2 className="h-title">Export palette</h2>
            <p className="h-sub">{shades.length} stops · base {baseHex}</p>
          </div>
          <button className="modal-close static" onClick={onClose}><CloseIcon /></button>
        </div>
        <div className="export-tabs">
          {tabs.map(t => (
            <button key={t.id}
              className={`export-tab ${tab === t.id ? 'active' : ''}`}
              onClick={() => setTab(t.id)}>
              {t.label}
            </button>
          ))}
          <div style={{ flex: 1 }} />
          <button
            className="btn-primary sm"
            onClick={() => onCopy(active.text, `exp-${active.id}`)}
          >
            {copiedTag === `exp-${active.id}`
              ? (<><CheckIcon /> Copied</>)
              : (<><CopyIcon /> Copy</>)}
          </button>
        </div>
        <pre className="export-code"><code>{active.text}</code></pre>
      </div>
    </div>
  );
}

function scaleFromCount(n) {
  // Map N stops to Tailwind-ish numeric keys (50, 100, 200, ..., 950)
  if (n <= 0) return [];
  if (n === 1) return ['500'];
  const out = [];
  for (let i = 0; i < n; i++) {
    const t = i / (n - 1);
    const v = Math.round(50 + t * 900);
    out.push(String(Math.max(50, Math.min(950, roundToStep(v, 50)))));
  }
  // dedupe if collisions
  const seen = new Set();
  return out.map(v => {
    let k = v, n = 0;
    while (seen.has(k)) { n++; k = v + '-' + n; }
    seen.add(k);
    return k;
  });
}
function roundToStep(n, step) { return Math.round(n / step) * step; }

// ─── UI Preview ──────────────────────────────────────────────────────────────
function UIPreview({ shades, baseHex, dark }) {
  const n = shades.length;
  const get = t => shades[Math.max(0, Math.min(n - 1, Math.round(t * (n - 1))))].hex;

  // Use the actual selected brand color
  const primaryHex = baseHex;
  const primaryRgb = CUm.hexToRgb(primaryHex);
  const primaryHiHex = get(dark ? 0.44 : 0.58);

  // White or black on primary
  const primaryFg = CUm.contrastRatio(primaryRgb, { r: 255, g: 255, b: 255 }) >= 3
    ? '#FFFFFF' : '#0A0A0A';

  // Very subtle tint: 10% brand blended into neutral bg
  const bgBase = dark ? 26 : 255;
  const blend = ch => Math.round(ch * 0.10 + bgBase * 0.90);
  const accentHex = CUm.rgbToHex({ r: blend(primaryRgb.r), g: blend(primaryRgb.g), b: blend(primaryRgb.b) });

  const c = {
    bg:        dark ? '#111111' : '#FFFFFF',
    surface:   dark ? '#1A1A1A' : '#F7F7F7',
    border:    dark ? '#2C2C2C' : '#E0E0E0',
    text:      dark ? '#EFEFEF' : '#0A0A0A',
    muted:     dark ? '#666666' : '#909090',
    primary:   primaryHex,
    primaryHi: primaryHiHex,
    primaryFg,
    accent:    accentHex,
  };

  return (
    <div className="preview" style={{
      '--p-bg': c.bg, '--p-surface': c.surface, '--p-border': c.border,
      '--p-text': c.text, '--p-muted': c.muted, '--p-primary': c.primary,
      '--p-primary-hi': c.primaryHi, '--p-primary-fg': c.primaryFg, '--p-accent': c.accent,
    }}>

      {/* Nav bar */}
      <div className="pv-nav">
        <div className="pv-nav-logo" style={{ background: c.primary, color: c.primaryFg }}>◆</div>
        <div className="pv-nav-links">
          <span className="pv-nav-link active">Dashboard</span>
          <span className="pv-nav-link">Projects</span>
          <span className="pv-nav-link">Analytics</span>
          <span className="pv-nav-link">Team</span>
        </div>
        <div className="pv-nav-right">
          <div className="pv-nav-search">Search…</div>
          <div className="pv-nav-avatar" style={{ background: c.primary, color: c.primaryFg }}>JD</div>
        </div>
      </div>

      <div className="pv-grid">
        {/* Card 1: project */}
        <div className="pv-card">
          <div className="pv-card-head">
            <div className="pv-avatar" style={{ background: c.primary, color: c.primaryFg }}>◆</div>
            <div>
              <div className="pv-card-title">Shipping route</div>
              <div className="pv-card-sub">Updated 3 min ago</div>
            </div>
            <span className="pv-chip">Live</span>
          </div>
          <div className="pv-card-body">
            <div className="pv-row"><span>Status</span><strong>On track</strong></div>
            <div className="pv-bar-wrap"><div className="pv-bar" style={{ width: '68%' }} /></div>
            <div className="pv-row small"><span>68% complete</span><span>12 days left</span></div>
          </div>
          <div className="pv-card-foot">
            <button className="pv-btn ghost">Details</button>
            <button className="pv-btn primary">Continue</button>
          </div>
        </div>

        {/* Card 2: form */}
        <div className="pv-card">
          <div className="pv-card-head">
            <div>
              <div className="pv-card-title">Create project</div>
              <div className="pv-card-sub">Fill out the details below</div>
            </div>
          </div>
          <div className="pv-card-body">
            <label className="pv-label">Project name</label>
            <input className="pv-input" defaultValue="Atlas redesign" />
            <label className="pv-label">Visibility</label>
            <div className="pv-seg">
              <button className="pv-seg-btn active">Private</button>
              <button className="pv-seg-btn">Team</button>
              <button className="pv-seg-btn">Public</button>
            </div>
            <div className="pv-checks">
              <label className="pv-check"><span className="pv-box checked" /> Enable notifications</label>
              <label className="pv-check"><span className="pv-box" /> Archive old activity</label>
            </div>
          </div>
          <div className="pv-card-foot">
            <button className="pv-btn ghost">Cancel</button>
            <button className="pv-btn primary">Create</button>
          </div>
        </div>

        {/* Card 3: stats */}
        <div className="pv-card stats">
          <div className="pv-stat">
            <div className="pv-stat-lbl">Revenue</div>
            <div className="pv-stat-val">$48,210</div>
            <div className="pv-stat-delta up">+12.4%</div>
          </div>
          <div className="pv-stat">
            <div className="pv-stat-lbl">Active users</div>
            <div className="pv-stat-val">3,420</div>
            <div className="pv-stat-delta up">+3.1%</div>
          </div>
          <div className="pv-sparkline">
            <svg viewBox="0 0 120 40" preserveAspectRatio="none" width="100%" height="40">
              <polyline fill="none" stroke={c.primary} strokeWidth="2"
                points="0,30 15,25 30,28 45,18 60,22 75,12 90,16 105,8 120,10" />
              <polyline fill={c.primary} fillOpacity=".15" stroke="none"
                points="0,30 15,25 30,28 45,18 60,22 75,12 90,16 105,8 120,10 120,40 0,40" />
            </svg>
          </div>
          <div className="pv-tags">
            <span className="pv-tag">Design</span>
            <span className="pv-tag">Engineering</span>
            <span className="pv-tag filled">New</span>
          </div>
        </div>

        {/* Card 4: notifications */}
        <div className="pv-card">
          <div className="pv-card-head">
            <div className="pv-card-title">Notifications</div>
            <span className="pv-chip">3 new</span>
          </div>
          <div className="pv-card-body">
            {[
              { text: 'Sprint 4 marked complete', time: '2m',  unread: true },
              { text: 'Sarah left a comment',     time: '15m', unread: true },
              { text: 'New release deployed',      time: '1h',  unread: false },
              { text: 'Invoice #1042 paid',         time: '3h',  unread: false },
            ].map((n, i) => (
              <div key={i} className="pv-notif">
                <div className="pv-notif-dot" style={{ background: n.unread ? c.primary : 'transparent', border: n.unread ? 'none' : `1.5px solid var(--p-border)` }} />
                <span className="pv-notif-text" style={{ opacity: n.unread ? 1 : 0.55 }}>{n.text}</span>
                <span className="pv-notif-time">{n.time}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Card 5: team */}
        <div className="pv-card">
          <div className="pv-card-head">
            <div className="pv-card-title">Team</div>
            <button className="pv-btn primary" style={{ padding: '4px 10px', fontSize: '11px' }}>+ Invite</button>
          </div>
          <div className="pv-card-body">
            {[
              { initials: 'AK', name: 'Anna Kim',    role: 'Designer',  online: true },
              { initials: 'BM', name: 'Bob Morris',  role: 'Engineer',  online: true },
              { initials: 'CL', name: 'Chris Lane',  role: 'Product',   online: false },
              { initials: 'DW', name: 'Dana White',  role: 'Marketing', online: false },
            ].map((m, i) => (
              <div key={i} className="pv-member">
                <div className="pv-member-av" style={{ background: c.accent, color: c.primary }}>{m.initials}</div>
                <div className="pv-member-info">
                  <div className="pv-member-name">{m.name}</div>
                  <div className="pv-member-role">{m.role}</div>
                </div>
                <div className="pv-member-status" style={{ background: m.online ? c.primary : 'var(--p-border)' }} />
              </div>
            ))}
          </div>
        </div>

        {/* Card 6: settings */}
        <div className="pv-card">
          <div className="pv-card-head">
            <div className="pv-card-title">Preferences</div>
          </div>
          <div className="pv-card-body">
            {[
              { label: 'Email notifications', on: true },
              { label: 'Public profile',      on: false },
              { label: 'Two-factor auth',     on: true },
              { label: 'Activity digest',     on: false },
            ].map((s, i) => (
              <div key={i} className="pv-toggle-row">
                <span className="pv-toggle-label">{s.label}</span>
                <div className="pv-toggle" style={{ background: s.on ? c.primary : 'var(--p-border)' }}>
                  <div className="pv-toggle-knob" style={{ transform: s.on ? 'translateX(14px)' : 'translateX(2px)' }} />
                </div>
              </div>
            ))}
          </div>
          <div className="pv-card-foot">
            <button className="pv-btn ghost">Reset</button>
            <button className="pv-btn primary">Save</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ShadeDetailModal, ExportModal, UIPreview });
