// shell.jsx — Sidebar, TopBar, PromptBar, ControlsPanel, HistoryStrip, DetailModal

const { useState: shUseState, useEffect: shUseEffect, useRef: shUseRef } = React;

// ─── Sidebar (left mode rail) ─────────────────────────────────────────────
const MODES = [
  { id: 't2i',        label: 'Text → Görsel',   Icon: IconT2I,        hint: '⌘1' },
  { id: 'i2i',        label: 'Görsel → Görsel', Icon: IconI2I,        hint: '⌘2' },
  { id: 'inpaint',    label: 'Inpaint',         Icon: IconInpaint,    hint: '⌘3' },
  { id: 'outpaint',   label: 'Outpaint',        Icon: IconOutpaint,   hint: '⌘4' },
  { id: 'variations', label: 'Varyasyon',       Icon: IconVariations, hint: '⌘5' },
  { id: 'sketch',     label: 'Eskiz → Görsel',  Icon: IconSketch,     hint: '⌘6' },
];

function Sidebar({ mode, onMode, theme, onTheme, onNew }) {
  return (
    <aside className="ai-rail">
      <div className="ai-rail-brand" aria-label="AI Image Lab">
        <div className="ai-brand-mark">
          <GenSVG prompt="brand" seed={1337}
                  style={{ width: '100%', height: '100%', borderRadius: 'inherit' }} />
        </div>
      </div>

      <button className="ai-rail-new" onClick={onNew} aria-label="Yeni iş">
        <IconPlus size={20} />
      </button>

      <nav className="ai-rail-nav">
        {MODES.map((m) => (
          <IconButton
            key={m.id}
            label={`${m.label}  ·  ${m.hint}`}
            side="right"
            active={mode === m.id}
            onClick={() => onMode(m.id)}
          >
            <m.Icon size={22} stroke={1.5} />
          </IconButton>
        ))}
      </nav>

      <div className="ai-rail-bottom">
        <IconButton
          label={theme === 'dark' ? 'Açık temaya geç' : 'Koyu temaya geç'}
          side="right"
          onClick={() => onTheme(theme === 'dark' ? 'light' : 'dark')}
        >
          {theme === 'dark' ? <IconSun size={20} /> : <IconMoon size={20} />}
        </IconButton>
        <IconButton label="Ayarlar" side="right"><IconSettings size={20} /></IconButton>
      </div>
    </aside>
  );
}

// ─── Top bar ──────────────────────────────────────────────────────────────
function TopBar({ mode, results, inspectorOpen, onToggleInspector, onOpenHistory }) {
  const modeMeta = MODES.find((m) => m.id === mode) || MODES[0];
  return (
    <header className="ai-topbar">
      <div className="ai-topbar-left">
        <div className="ai-topbar-title">
          <h1>AI Image Lab</h1>
          <span className="ai-topbar-sep">·</span>
          <span className="ai-topbar-mode">{modeMeta.label}</span>
        </div>
      </div>
      <div className="ai-topbar-right">
        <IconButton label="Tüm geçmiş" side="bottom" onClick={onOpenHistory}>
          <IconClock size={18} />
        </IconButton>
        <IconButton
          label={inspectorOpen ? 'Paneli kapat' : 'Ayar panelini aç'}
          side="bottom"
          onClick={onToggleInspector}
          active={inspectorOpen}
        >
          <IconSettings size={18} />
        </IconButton>
      </div>
    </header>
  );
}

// ─── Prompt bar (floating) ────────────────────────────────────────────────
function PromptBar({
  prompt, onPrompt, onSubmit, onImprove,
  model, onModel, modelOptions,
  generating, canSubmit, mode, onShufflePrompt,
}) {
  const textareaRef = shUseRef(null);

  shUseEffect(() => {
    const el = textareaRef.current;
    if (!el) return;
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 180) + 'px';
  }, [prompt]);

  const onKey = (e) => {
    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
      e.preventDefault();
      if (canSubmit) onSubmit();
    } else if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (canSubmit) onSubmit();
    }
  };

  const placeholder = {
    t2i: 'Hayalini yaz... örn: çay bardağında küçük bir orman, makro foto',
    i2i: 'Bu referans neye dönüşsün? örn: aynı kompozisyon, akvarel stilinde',
    inpaint: 'Maskelenen alan neye dönüşsün? örn: bir kuş, soft ışık',
    outpaint: 'Yeni alanlar nasıl görünsün? örn: deniz manzarası, açık gökyüzü',
    variations: 'İsteğe bağlı: stil notunu güncelle, sonra ⏎',
    sketch: 'Eskizini neye dönüştürelim? örn: gece şehri, sinematik',
  }[mode];

  return (
    <div className="ai-promptbar-wrap">
      <div className={`ai-promptbar ${generating ? 'is-busy' : ''}`}>
        <Dropdown
          value={model}
          options={modelOptions}
          onChange={onModel}
          renderValue={(o) => (
            <span className="ai-modelpill">
              <span className="ai-modelpill-dot" />
              <span className="ai-modelpill-name">{o?.label}</span>
            </span>
          )}
          renderItem={(o) => (
            <span className="ai-modelitem">
              <span className="ai-modelitem-name">{o.label}</span>
              <span className="ai-modelitem-tag">{o.tag}</span>
            </span>
          )}
        />

        <div className="ai-promptbar-input">
          <textarea
            ref={textareaRef}
            value={prompt}
            onChange={(e) => onPrompt(e.target.value)}
            onKeyDown={onKey}
            placeholder={placeholder}
            rows={1}
          />
        </div>

        <div className="ai-promptbar-actions">
          <Tooltip label="Şaşırt — örnek prompt" side="top">
            <button className="ai-mini" onClick={onShufflePrompt} aria-label="Örnek prompt">
              <IconDice size={16} />
            </button>
          </Tooltip>
          <Tooltip label="AI ile iyileştir" side="top">
            <button className="ai-mini" onClick={onImprove} aria-label="Prompt iyileştir">
              <IconSparkle size={16} />
            </button>
          </Tooltip>
          <button
            className="ai-submit"
            disabled={!canSubmit}
            onClick={onSubmit}
            aria-label="Üret"
          >
            {generating ? <Spinner size={16} /> : <IconSend size={16} />}
            <span>{generating ? 'Üretiyor' : 'Üret'}</span>
          </button>
        </div>
      </div>

      <div className="ai-promptbar-hint">
        <span><kbd>⏎</kbd> üret</span>
        <span><kbd>shift</kbd>+<kbd>⏎</kbd> yeni satır</span>
        <span><kbd>⌘</kbd>+<kbd>K</kbd> hızlı menü</span>
      </div>
    </div>
  );
}

// ─── Controls panel (right inspector) ─────────────────────────────────────
function ControlsPanel({
  open, onClose, state, dispatch, modelLabel,
  apiKey, onApiKey, imageOnly, onImageOnly,
  modelsLoading, modelsError, liveModelsCount,
}) {
  if (!open) return null;
  const showRefWeight = ['i2i', 'inpaint', 'outpaint', 'variations'].includes(state.mode);
  const [keyDraft, setKeyDraft] = shUseState(apiKey || '');
  const [keyEditing, setKeyEditing] = shUseState(!apiKey);
  shUseEffect(() => { setKeyDraft(apiKey || ''); setKeyEditing(!apiKey); }, [apiKey]);

  return (
    <aside className="ai-inspector">
      <div className="ai-inspector-head">
        <h3>Ayarlar</h3>
        <IconButton label="Kapat" side="bottom" onClick={onClose}>
          <IconClose size={16} />
        </IconButton>
      </div>

      <div className="ai-inspector-body">
        <Field
          label="OpenRouter"
          hint={
            modelsError
              ? `Modeller alınamadı: ${modelsError}`
              : modelsLoading
                ? 'Modeller yükleniyor…'
                : liveModelsCount
                  ? `${liveModelsCount} canlı görsel modeli yüklü.`
                  : 'Modeller boş — anahtarı kontrol et veya tekrar dene.'
          }
        >
          {keyEditing ? (
            <div style={{ display: 'flex', gap: 6 }}>
              <input
                className="ai-input"
                type="password"
                value={keyDraft}
                placeholder="sk-or-v1-..."
                autoComplete="off"
                spellCheck={false}
                onChange={(e) => setKeyDraft(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') { onApiKey(keyDraft.trim()); setKeyEditing(false); }
                }}
                style={{ flex: 1, minWidth: 0 }}
              />
              <button className="ai-link" style={{ whiteSpace: 'nowrap' }}
                onClick={() => { onApiKey(keyDraft.trim()); setKeyEditing(false); }}>
                Kaydet
              </button>
            </div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6 }}>
              <code style={{ color: 'var(--ai-muted)', fontSize: 12 }}>
                {apiKey.slice(0, 8)}…{apiKey.slice(-4)}
              </code>
              <span style={{ display: 'flex', gap: 8 }}>
                <button className="ai-link" onClick={() => setKeyEditing(true)}>Değiştir</button>
                <button className="ai-link" onClick={() => { onApiKey(''); setKeyEditing(true); setKeyDraft(''); }}>Sil</button>
              </span>
            </div>
          )}
          <div style={{ marginTop: 8 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--ai-ink-2)', cursor: 'pointer' }}>
              <input type="checkbox" checked={imageOnly}
                     onChange={(e) => onImageOnly(e.target.checked)}
                     style={{ accentColor: 'var(--ai-accent)' }} />
              <span>Sadece görsel modeli olanları listele</span>
            </label>
          </div>
        </Field>

        <Field label="Boyut / En-Boy">
          <AspectPicker value={state.aspect} onChange={(v) => dispatch({ type: 'set', key: 'aspect', value: v })} />
        </Field>

        <Field label="Adet" hint="Her seferinde kaç farklı görsel üretelim">
          <Segmented
            value={state.batch}
            onChange={(v) => dispatch({ type: 'set', key: 'batch', value: v })}
            options={[1, 2, 3, 4].map((n) => ({ value: n, label: String(n) }))}
          />
        </Field>

        {showRefWeight && (
          <Field
            label="Referans etkisi"
            hint={`%${state.refWeight} · referansa ${state.refWeight > 60 ? 'çok yakın' : state.refWeight > 30 ? 'orta düzey' : 'gevşek'} bağlı kal`}
          >
            <Slider
              value={state.refWeight}
              min={0}
              max={100}
              step={1}
              onChange={(v) => dispatch({ type: 'set', key: 'refWeight', value: v })}
              fmt={(v) => `${v}%`}
            />
          </Field>
        )}

        <Field label="Negatif prompt" hint="Olmasını istemediğin şeyleri yaz">
          <textarea
            className="ai-textarea"
            rows={3}
            value={state.negative}
            placeholder="örn: bulanık, tekrar eden eller, watermark"
            onChange={(e) => dispatch({ type: 'set', key: 'negative', value: e.target.value })}
          />
        </Field>

        <Field
          label="Seed"
          action={
            <button className="ai-link" onClick={() => dispatch({ type: 'set', key: 'seed', value: Math.floor(Math.random() * 1e9) })}>
              <IconDice size={13} /> rastgele
            </button>
          }
          hint="Aynı seed + aynı prompt = aynı görsel"
        >
          <input
            className="ai-input"
            type="number"
            value={state.seed ?? ''}
            placeholder="rastgele"
            onChange={(e) => dispatch({ type: 'set', key: 'seed', value: e.target.value ? Number(e.target.value) : null })}
          />
        </Field>

        <Field label="Stil tonu" hint="Promptuna kısayol ekler">
          <div className="ai-chips-wrap">
            {STYLE_PRESETS.map((p) => (
              <button
                key={p}
                className={`ai-chip ${state.stylePresets.includes(p) ? 'is-active' : ''}`}
                onClick={() => dispatch({ type: 'togglePreset', value: p })}
              >
                {p}
              </button>
            ))}
          </div>
        </Field>

        <div className="ai-inspector-summary">
          <div><span>Model</span><span>{modelLabel}</span></div>
          <div><span>Tahmini süre</span><span>~{2 + state.batch * 2}s</span></div>
          <div><span>Tahmini kredi</span><span>{(0.012 * state.batch).toFixed(3)}</span></div>
        </div>
      </div>
    </aside>
  );
}

// ─── History strip (bottom, expandable) ───────────────────────────────────
function HistoryStrip({ results, onOpen, onLoadPrompt, onSetAsRef }) {
  const recent = results.slice(0, 20);
  if (!recent.length) return null;
  return (
    <div className="ai-history-strip">
      <div className="ai-history-strip-head">
        <span className="ai-history-strip-title">Geçmiş</span>
        <span className="ai-history-strip-count">{results.length}</span>
      </div>
      <div className="ai-history-strip-row">
        {recent.map((r) => (
          <div key={r.id} className="ai-history-card">
            <Thumb prompt={r.prompt} seed={r.seed} imageUrl={r.imageUrl} size={64} radius={10}
                   onClick={() => onOpen(r)} favorite={r.favorite} />
            <div className="ai-history-card-meta">
              <span className="ai-history-prompt" title={r.prompt}>{r.prompt}</span>
              <span className="ai-history-tools">
                <button onClick={() => onLoadPrompt(r.prompt)}>prompt’u kullan</button>
                <span>·</span>
                <button onClick={() => onSetAsRef(r)}>referans yap</button>
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Detail modal ─────────────────────────────────────────────────────────
function DetailModal({ result, onClose, onFavorite, onLoadPrompt, onSetAsRef }) {
  shUseEffect(() => {
    const k = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [onClose]);
  if (!result) return null;
  return (
    <div className="ai-modal" onClick={onClose}>
      <div className="ai-modal-card" onClick={(e) => e.stopPropagation()}>
        <div className="ai-modal-image" style={{ aspectRatio: result.aspectRatio || 1 }}>
          {result.imageUrl ? (
            <img src={result.imageUrl} alt={result.prompt}
                 style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          ) : (
            <GenSVG prompt={result.prompt} seed={result.seed}
                    style={{ width: '100%', height: '100%', display: 'block' }} />
          )}
        </div>
        <div className="ai-modal-side">
          <div className="ai-modal-side-head">
            <div>
              <span className="ai-modal-eyebrow">{result.modeLabel}</span>
              <h2>{result.prompt}</h2>
            </div>
            <IconButton label="Kapat" onClick={onClose}><IconClose size={16} /></IconButton>
          </div>

          <dl className="ai-modal-dl">
            <div><dt>Model</dt><dd>{result.modelLabel}</dd></div>
            <div><dt>Boyut</dt><dd>{result.aspect}</dd></div>
            <div><dt>Seed</dt><dd>{result.seed}</dd></div>
            <div><dt>Oluşturma</dt><dd>{result.t}</dd></div>
            {result.negative ? <div><dt>Negatif</dt><dd>{result.negative}</dd></div> : null}
            {result.refWeight != null ? <div><dt>Ref. etkisi</dt><dd>%{result.refWeight}</dd></div> : null}
          </dl>

          <div className="ai-modal-actions">
            <Button variant="primary" icon={<IconDownload size={16} />}>İndir (PNG)</Button>
            <Button icon={result.favorite ? <IconHeartFill size={16} /> : <IconHeart size={16} />}
                    onClick={() => onFavorite(result.id)}>
              {result.favorite ? 'Favoride' : 'Favori'}
            </Button>
            <Button icon={<IconCopy size={16} />} onClick={() => onLoadPrompt(result.prompt)}>
              Prompt’u kullan
            </Button>
            <Button icon={<IconImage size={16} />} onClick={() => onSetAsRef(result)}>
              Referans yap
            </Button>
            <Button icon={<IconShare size={16} />}>Paylaş</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Quick command palette (⌘K) — light version ───────────────────────────
function CommandPalette({ open, onClose, onCommand, results }) {
  const [q, setQ] = shUseState('');
  shUseEffect(() => {
    if (!open) setQ('');
  }, [open]);
  if (!open) return null;

  const commands = [
    ...MODES.map((m) => ({ id: `mode:${m.id}`, label: `Mode: ${m.label}`, run: () => onCommand({ type: 'setMode', value: m.id }) })),
    { id: 'theme:toggle', label: 'Tema: aç/kapat', run: () => onCommand({ type: 'toggleTheme' }) },
    { id: 'improve', label: 'Prompt: AI ile iyileştir', run: () => onCommand({ type: 'improvePrompt' }) },
    { id: 'random', label: 'Prompt: örnek koy', run: () => onCommand({ type: 'shufflePrompt' }) },
    ...STARTER_PROMPTS.slice(0, 4).map((p, i) => ({ id: `p${i}`, label: `Prompt: ${p}`, run: () => onCommand({ type: 'usePrompt', value: p }) })),
    ...results.slice(0, 6).map((r) => ({ id: `r-${r.id}`, label: `Aç: ${r.prompt}`, run: () => onCommand({ type: 'openResult', value: r }) })),
  ];
  const matches = q
    ? commands.filter((c) => c.label.toLowerCase().includes(q.toLowerCase()))
    : commands.slice(0, 10);

  return (
    <div className="ai-cmd-overlay" onClick={onClose}>
      <div className="ai-cmd" onClick={(e) => e.stopPropagation()}>
        <input
          autoFocus
          className="ai-cmd-input"
          placeholder="Komut, mode veya prompt ara..."
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Escape') onClose();
            if (e.key === 'Enter' && matches[0]) { matches[0].run(); onClose(); }
          }}
        />
        <div className="ai-cmd-list">
          {matches.length ? matches.map((c) => (
            <button key={c.id} className="ai-cmd-item" onClick={() => { c.run(); onClose(); }}>
              {c.label}
            </button>
          )) : <div className="ai-cmd-empty">Eşleşen yok</div>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Sidebar, TopBar, PromptBar, ControlsPanel,
  HistoryStrip, DetailModal, CommandPalette, MODES,
});
