// model-picker.jsx — model registry + reusable model selector component.
// Used by image-tool.jsx and video-tool.jsx, but works for any tool.
//
// To add a new model: append an entry to MODELS_REGISTRY below.

const MODELS_REGISTRY = {
  image: [
    {
      id: 'flux-pro', name: 'Flux Pro', vendor: 'Black Forest Labs',
      desc: 'Best photoreal & prompt adherence. Slower, premium quality.',
      credits: 4, speed: 'slow', quality: 5,
      tags: ['Photoreal', 'Best quality'],
      hue: 200, badge: 'PRO',
    },
    {
      id: 'sdxl-turbo', name: 'SDXL Turbo', vendor: 'Stability AI',
      desc: 'Fast, balanced quality. Great default for everyday work.',
      credits: 1, speed: 'fast', quality: 4,
      tags: ['Fast', 'Default'],
      hue: 280, badge: null,
    },
    {
      id: 'midjourney-v6', name: 'MJ v6', vendor: 'Midjourney',
      desc: 'Cinematic, painterly aesthetic. Strong on mood and lighting.',
      credits: 3, speed: 'medium', quality: 5,
      tags: ['Cinematic', 'Artistic'],
      hue: 30, badge: null,
    },
    {
      id: 'imagen-3', name: 'Imagen 3', vendor: 'Google',
      desc: 'Best for typography in image, signage, complex layouts.',
      credits: 3, speed: 'medium', quality: 5,
      tags: ['Text-in-image', 'Layout'],
      hue: 340, badge: null,
    },
    {
      id: 'dalle-3', name: 'DALL·E 3', vendor: 'OpenAI',
      desc: 'Best instruction following. Reliable for specific scenes.',
      credits: 2, speed: 'medium', quality: 4,
      tags: ['Instruction', 'Reliable'],
      hue: 160, badge: null,
    },
    {
      id: 'recraft-v3', name: 'Recraft v3', vendor: 'Recraft',
      desc: 'Vector & icon style. Editable strokes and brand-ready.',
      credits: 2, speed: 'fast', quality: 4,
      tags: ['Vector', 'Icons'],
      hue: 100, badge: 'NEW',
    },
  ],
  video: [
    {
      id: 'sora-turbo', name: 'Sora Turbo', vendor: 'OpenAI',
      desc: 'High coherence, longer clips, best for scenes with motion.',
      credits: 24, speed: 'slow', quality: 5,
      tags: ['Best motion', '8s max'],
      hue: 220, badge: 'PRO',
    },
    {
      id: 'veo-3', name: 'Veo 3', vendor: 'Google',
      desc: 'Photoreal & cinematic. Strong on landscapes, characters.',
      credits: 18, speed: 'slow', quality: 5,
      tags: ['Photoreal', '4K'],
      hue: 200, badge: null,
    },
    {
      id: 'kling-2', name: 'Kling 2.0', vendor: 'Kuaishou',
      desc: 'Excellent character consistency and physics simulation.',
      credits: 12, speed: 'medium', quality: 4,
      tags: ['Character', 'Physics'],
      hue: 340, badge: null,
    },
    {
      id: 'runway-gen4', name: 'Runway Gen-4', vendor: 'Runway',
      desc: 'Fast iteration. Great for image-to-video and stylized clips.',
      credits: 8, speed: 'fast', quality: 4,
      tags: ['Fast', 'i2v'],
      hue: 280, badge: null,
    },
    {
      id: 'luma-ray', name: 'Luma Ray 2', vendor: 'Luma Labs',
      desc: 'Smooth camera moves. Best when you need controlled motion.',
      credits: 10, speed: 'medium', quality: 4,
      tags: ['Camera', 'Smooth'],
      hue: 30, badge: null,
    },
    {
      id: 'pika-2', name: 'Pika 2.0', vendor: 'Pika Labs',
      desc: 'Playful, stylized. Cheap iteration for quick concepts.',
      credits: 6, speed: 'fast', quality: 3,
      tags: ['Stylized', 'Cheap'],
      hue: 100, badge: null,
    },
  ],
};

// ---- ModelCard: a single picker tile ----
const ModelCard = ({ model, selected, onClick, accent }) => {
  const speedLabel = { fast: '⚡ Fast', medium: '~ Medium', slow: '◐ Slow' }[model.speed];
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', padding: 12, borderRadius: 10,
      background: selected ? `linear-gradient(180deg, ${accent}14, ${accent}06)` : 'rgba(255,255,255,0.025)',
      border: '1px solid ' + (selected ? accent + '66' : 'var(--line-2)'),
      boxShadow: selected ? `0 0 0 3px ${accent}1a` : 'none',
      cursor: 'pointer', transition: 'all .12s', position: 'relative',
      display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      {model.badge && (
        <span style={{
          position: 'absolute', top: 10, right: 10, fontSize: 11, fontWeight: 700,
          padding: '2px 6px', borderRadius: 4, letterSpacing: '0.06em',
          background: model.badge === 'PRO' ? 'linear-gradient(90deg, #fbbf24, #f97316)' : 'rgba(74,222,128,0.18)',
          color: model.badge === 'PRO' ? '#1c1207' : '#86efac',
          border: model.badge === 'NEW' ? '1px solid rgba(74,222,128,0.3)' : 'none',
        }}>{model.badge}</span>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {(() => { const h = model.hue ?? 200; return (
        <div style={{
          width: 28, height: 28, borderRadius: 7, flexShrink: 0,
          background: `radial-gradient(circle at 30% 30%, hsl(${h} 80% 60%), hsl(${h + 30} 70% 30%))`,
          border: `1px solid hsl(${h} 60% 40% / 0.6)`,
          boxShadow: `0 0 12px hsl(${h} 70% 50% / 0.3)`,
        }} />); })()}
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)', lineHeight: 1.2 }}>{model.name}</div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{model.vendor}</div>
        </div>
      </div>
      <div style={{ fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.4, minHeight: 32 }}>{model.desc}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 6, borderTop: '1px solid var(--line)' }}>
        <span style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>{speedLabel}</span>
        <span style={{
          fontSize: 11, color: selected ? accent : 'var(--fg-1)', fontWeight: 600,
          display: 'inline-flex', alignItems: 'center', gap: 3,
        }}>
          <Icon name="coin" size={10} /> {model.credits}
        </span>
      </div>
    </button>
  );
};

// ---- ModelPicker: full inline grid + collapsible "show all" ----
const ModelPicker = ({ kind = 'image', value, onChange, accent = '#22d3ee', compareMode, onCompareToggle, compareModels = [] }) => {
  const models = MODELS_REGISTRY[kind] || [];
  const [expanded, setExpanded] = React.useState(false);
  const visible = expanded ? models : models.slice(0, 4);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>
          Model · {models.length} available
        </div>
        {onCompareToggle && (
          <button onClick={onCompareToggle} style={{
            border: 'none', background: 'transparent', padding: '4px 8px', borderRadius: 6,
            fontSize: 11, color: compareMode ? accent : 'var(--fg-3)', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 4, fontWeight: 500,
          }}>
            <Icon name="layers" size={11} />
            {compareMode ? `Comparing ${compareModels.length}` : 'Compare'}
          </button>
        )}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {visible.map(m => {
          const isSelected = compareMode ? compareModels.includes(m.id) : value === m.id;
          return (
            <div key={m.id} style={{ position: 'relative' }}>
              <ModelCard
                model={m}
                selected={isSelected}
                accent={accent}
                onClick={() => {
                  if (compareMode) {
                    const next = compareModels.includes(m.id)
                      ? compareModels.filter(id => id !== m.id)
                      : compareModels.length < 4 ? [...compareModels, m.id] : compareModels;
                    onChange(next);
                  } else {
                    onChange(m.id);
                  }
                }}
              />
              {compareMode && isSelected && (
                <div style={{
                  position: 'absolute', top: 8, left: 8,
                  width: 18, height: 18, borderRadius: 999,
                  background: accent, color: '#06080f',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10, fontWeight: 700,
                }}>{compareModels.indexOf(m.id) + 1}</div>
              )}
            </div>
          );
        })}
      </div>

      {models.length > 4 && (
        <button onClick={() => setExpanded(e => !e)} style={{
          width: '100%', marginTop: 10, height: 30, borderRadius: 8,
          background: 'rgba(255,255,255,0.025)', border: '1px dashed var(--line-2)',
          color: 'var(--fg-2)', fontSize: 12, cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
        }}>
          <Icon name={expanded ? 'chevronDown' : 'plus'} size={11} />
          {expanded ? 'Show less' : `Show ${models.length - 4} more models`}
        </button>
      )}
    </div>
  );
};

Object.assign(window, { MODELS_REGISTRY, ModelPicker, ModelCard });
