// workspaces.jsx — mode-specific canvas areas. Each one renders into the
// central "stage" of the app. They share the prompt bar (rendered by the
// shell) but own everything inside the canvas.

const { useState: __wsUseState, useEffect: __wsUseEffect, useRef: __wsUseRef,
        useMemo: __wsUseMemo, useCallback: __wsUseCb } = React;

// ─── Result card (shared) ─────────────────────────────────────────────────
function ResultCard({ result, onOpen, onFavorite, onCopyPrompt, onDownload, size = 'lg' }) {
  return (
    <div className={`ai-result ai-result-${size}`}
         style={{ aspectRatio: result.aspectRatio || 1 }}>
      {result.imageUrl ? (
        <img src={result.imageUrl} alt={result.prompt}
             style={{ width: '100%', height: '100%', objectFit: 'cover',
                      display: 'block', borderRadius: 'inherit' }} />
      ) : (
        <GenSVG prompt={result.prompt} seed={result.seed}
                style={{ width: '100%', height: '100%', display: 'block', borderRadius: 'inherit' }} />
      )}
      <div className="ai-result-actions">
        <IconButton label={result.favorite ? 'Favorilerden çıkar' : 'Favorilere ekle'}
                    side="top" onClick={() => onFavorite(result.id)} active={result.favorite}>
          {result.favorite ? <IconHeartFill size={16} /> : <IconHeart size={16} />}
        </IconButton>
        <IconButton label="Prompt'u kopyala" side="top" onClick={() => onCopyPrompt(result.prompt)}>
          <IconCopy size={16} />
        </IconButton>
        <IconButton label="İndir" side="top" onClick={() => onDownload(result)}>
          <IconDownload size={16} />
        </IconButton>
      </div>
      <button className="ai-result-open" onClick={() => onOpen(result)} aria-label="Detayda aç">
        <span className="ai-result-meta">
          <span className="ai-result-model">{result.modelLabel}</span>
          <span className="ai-result-seed">seed · {result.seed.toString().slice(0, 6)}</span>
        </span>
      </button>
    </div>
  );
}

// ─── Empty / hero state ───────────────────────────────────────────────────
function EmptyStage({ mode, onTry }) {
  const COPY = {
    t2i:        ['Bir prompt yaz', 'Aşağıdaki çubuğa yazıp ⏎ ile başlat. Yeni bir görsel saniyeler içinde burada belirir.'],
    i2i:        ['Bir referans bırak', 'Sağdaki canvasa görsel sürükle veya örnek seç. Prompt’u yaz, varyasyon üret.'],
    inpaint:    ['Düzenlenecek alanı maskele', 'Önce bir görsel seç. Sonra fırça ile boyadığın alanı yeniden üretelim.'],
    outpaint:   ['Kanvası genişlet', 'Mevcut görseli yükle. Hangi yönlere doğru genişlemesini istediğini seç.'],
    variations: ['Varyasyon türet', 'Var olan bir görseli kaynak yap, modelin aynı temaya 4 farklı yorum getirsin.'],
    sketch:     ['Bir eskiz çiz', 'Kaba bir çizgi ve birkaç sözcük — model gerisini halleder.'],
  };
  const [title, sub] = COPY[mode] || COPY.t2i;
  const samples = STARTER_PROMPTS.slice(0, 3);
  return (
    <div className="ai-empty">
      <div className="ai-empty-art" aria-hidden="true">
        <GenSVG prompt={`empty-${mode}`} seed={42 + mode.length}
                style={{ width: '100%', height: '100%', display: 'block' }} />
      </div>
      <h2>{title}</h2>
      <p>{sub}</p>
      {mode === 't2i' || mode === 'i2i' || mode === 'sketch' ? (
        <div className="ai-empty-chips">
          {samples.map((s, i) => (
            <button key={i} className="ai-chip" onClick={() => onTry(s)}>
              <IconSparkle size={13} />{s.length > 64 ? s.slice(0, 64) + '…' : s}
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}

// ─── Loading state ────────────────────────────────────────────────────────
function GeneratingStage({ progress, eta, batch, aspect, prompt, onCancel }) {
  const cells = Array.from({ length: batch }, (_, i) => i);
  const ratio = aspectRatio(aspect);
  return (
    <div className="ai-gen-stage">
      <div className={`ai-gen-grid count-${batch}`}>
        {cells.map((i) => (
          <div key={i} className="ai-gen-cell" style={{ aspectRatio: ratio }}>
            <div className="ai-gen-shimmer">
              <GenSVG prompt={`${prompt}-${i}`} seed={hashStr(prompt) + i * 9973}
                      style={{ width: '100%', height: '100%', display: 'block',
                               filter: 'blur(18px)', transform: 'scale(1.15)' }} />
              <div className="ai-gen-shimmer-overlay" />
            </div>
          </div>
        ))}
      </div>
      <div className="ai-gen-hud">
        <div className="ai-gen-bar"><div className="ai-gen-bar-fill" style={{ width: `${progress}%` }} /></div>
        <div className="ai-gen-meta">
          <span>%{Math.round(progress)}</span>
          <span className="ai-gen-eta">{eta > 0 ? `~${eta}s kaldı` : 'son rötuş'}</span>
          <button className="ai-gen-cancel" onClick={onCancel}>
            <IconStop size={12} /> İptal
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Results grid ─────────────────────────────────────────────────────────
function ResultsGrid({ results, aspect, onOpen, onFavorite, onCopyPrompt, onDownload }) {
  return (
    <div className={`ai-results count-${results.length}`}>
      {results.map((r) => (
        <ResultCard key={r.id} result={r}
                    onOpen={onOpen} onFavorite={onFavorite}
                    onCopyPrompt={onCopyPrompt} onDownload={onDownload} />
      ))}
    </div>
  );
}

// ─── T2I workspace ────────────────────────────────────────────────────────
function T2IWorkspace(props) {
  const { state, dispatch, currentResults, onTryPrompt, openDetail } = props;
  if (state.generating) {
    return <GeneratingStage progress={state.progress} eta={state.eta}
              batch={state.batch} aspect={state.aspect} prompt={state.prompt}
              onCancel={() => dispatch({ type: 'cancel' })} />;
  }
  if (!currentResults.length) {
    return <EmptyStage mode="t2i" onTry={onTryPrompt} />;
  }
  return (
    <ResultsGrid results={currentResults} aspect={state.aspect}
                 onOpen={openDetail}
                 onFavorite={(id) => dispatch({ type: 'favorite', id })}
                 onCopyPrompt={(p) => navigator.clipboard?.writeText(p)}
                 onDownload={() => {}} />
  );
}

// ─── Reference drop zone (used by I2I / Inpaint / Outpaint / Variations) ──
function RefDropZone({ value, onChange, label }) {
  const [over, setOver] = useState(false);
  const inputRef = useRef(null);
  const pickFile = () => inputRef.current?.click();
  const handleFiles = (files) => {
    const file = files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => onChange({ src: reader.result, label: file.name });
    reader.readAsDataURL(file);
  };
  if (value) {
    return (
      <div className="ai-ref-card">
        {value.src ? (
          <img src={value.src} alt="" />
        ) : (
          <GenSVG prompt={value.prompt || 'ref'} seed={value.seed} style={{ width: '100%', height: '100%' }} />
        )}
        <div className="ai-ref-card-foot">
          <span className="ai-ref-card-lbl">{value.label || 'referans'}</span>
          <button className="ai-ref-card-x" onClick={() => onChange(null)} aria-label="Kaldır">
            <IconClose size={14} />
          </button>
        </div>
      </div>
    );
  }
  return (
    <div
      className={`ai-ref-drop ${over ? 'is-over' : ''}`}
      onDragEnter={(e) => { e.preventDefault(); setOver(true); }}
      onDragLeave={() => setOver(false)}
      onDragOver={(e) => e.preventDefault()}
      onDrop={(e) => { e.preventDefault(); setOver(false); handleFiles(e.dataTransfer.files); }}
      onClick={pickFile}
      role="button"
    >
      <input ref={inputRef} type="file" accept="image/*" hidden
             onChange={(e) => handleFiles(e.target.files)} />
      <div className="ai-ref-drop-icon"><IconUpload size={22} /></div>
      <div className="ai-ref-drop-title">{label || 'Bir görsel sürükle'}</div>
      <div className="ai-ref-drop-sub">veya tıkla — PNG / JPG / WEBP</div>
      <div className="ai-ref-drop-or">— veya bir örnekten başla —</div>
      <div className="ai-ref-drop-samples">
        {SAMPLE_HISTORY.slice(0, 4).map((s, i) => (
          <button key={i} className="ai-ref-sample"
                  onClick={(e) => { e.stopPropagation(); onChange({ prompt: s.prompt, seed: hashStr(s.prompt), label: s.prompt }); }}>
            <GenSVG prompt={s.prompt} seed={hashStr(s.prompt)}
                    style={{ width: '100%', height: '100%' }} />
          </button>
        ))}
      </div>
    </div>
  );
}

// ─── I2I workspace ────────────────────────────────────────────────────────
function I2IWorkspace(props) {
  const { state, dispatch, currentResults, onTryPrompt, openDetail } = props;
  return (
    <div className="ai-i2i">
      <div className="ai-i2i-source">
        <div className="ai-i2i-label">Referans</div>
        <RefDropZone value={state.refImage} onChange={(v) => dispatch({ type: 'setRef', value: v })} />
      </div>
      <div className="ai-i2i-arrow" aria-hidden="true"><IconArrow size={20} /></div>
      <div className="ai-i2i-result">
        <div className="ai-i2i-label">Sonuç</div>
        {state.generating ? (
          <GeneratingStage progress={state.progress} eta={state.eta} batch={1}
            aspect={state.aspect} prompt={state.prompt}
            onCancel={() => dispatch({ type: 'cancel' })} />
        ) : currentResults.length ? (
          <ResultsGrid results={currentResults.slice(0, 1)} aspect={state.aspect}
            onOpen={openDetail}
            onFavorite={(id) => dispatch({ type: 'favorite', id })}
            onCopyPrompt={(p) => navigator.clipboard?.writeText(p)}
            onDownload={() => {}} />
        ) : (
          <div className="ai-i2i-placeholder">
            <GenSVG prompt="placeholder" seed={777}
                    style={{ width: '100%', height: '100%', opacity: 0.18 }} />
            <div className="ai-i2i-placeholder-text">
              {state.refImage ? 'Prompt’u yaz ve ⏎' : 'Önce sol tarafa referans bırak'}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Mask painting canvas (for inpaint + sketch) ──────────────────────────
function PaintCanvas({ width, height, brushSize, mode = 'mask', background, onDirty, paintRef }) {
  // mode: 'mask' shows soft red translucent paint; 'sketch' shows dark ink lines.
  const canvasRef = useRef(null);
  const [drawing, setDrawing] = useState(false);
  const last = useRef(null);

  useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    c.width = width;
    c.height = height;
    const ctx = c.getContext('2d');
    ctx.clearRect(0, 0, width, height);
    if (paintRef) paintRef.current = { canvas: c, clear: () => { ctx.clearRect(0, 0, width, height); onDirty?.(false); } };
  }, [width, height]);

  const pos = (e) => {
    const rect = canvasRef.current.getBoundingClientRect();
    const cx = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left;
    const cy = (e.touches ? e.touches[0].clientY : e.clientY) - rect.top;
    return [(cx / rect.width) * width, (cy / rect.height) * height];
  };

  const start = (e) => {
    e.preventDefault();
    setDrawing(true);
    last.current = pos(e);
    paint(e);
  };
  const stop = () => {
    setDrawing(false);
    last.current = null;
  };
  const paint = (e) => {
    if (!drawing && e.type !== 'pointerdown') return;
    const ctx = canvasRef.current.getContext('2d');
    const [x, y] = pos(e);
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    if (mode === 'mask') {
      ctx.strokeStyle = 'rgba(255, 80, 120, 0.55)';
      ctx.lineWidth = brushSize;
    } else {
      ctx.strokeStyle = '#1d1d1f';
      ctx.lineWidth = brushSize;
    }
    if (last.current) {
      ctx.beginPath();
      ctx.moveTo(last.current[0], last.current[1]);
      ctx.lineTo(x, y);
      ctx.stroke();
    } else {
      ctx.beginPath();
      ctx.arc(x, y, brushSize / 2, 0, Math.PI * 2);
      ctx.fillStyle = ctx.strokeStyle;
      ctx.fill();
    }
    last.current = [x, y];
    onDirty?.(true);
  };

  return (
    <div className="ai-paint" style={{ background }}>
      <canvas
        ref={canvasRef}
        className="ai-paint-canvas"
        onPointerDown={start}
        onPointerMove={(e) => drawing && paint(e)}
        onPointerUp={stop}
        onPointerLeave={stop}
      />
    </div>
  );
}

// ─── Inpaint workspace ────────────────────────────────────────────────────
function InpaintWorkspace(props) {
  const { state, dispatch, currentResults, openDetail } = props;
  const [brush, setBrush] = useState(48);
  const [dirty, setDirty] = useState(false);
  const paintRef = useRef(null);
  const ratio = aspectRatio(state.aspect);

  if (!state.refImage) {
    return (
      <div className="ai-mode-empty">
        <div className="ai-mode-empty-inner">
          <h3>Düzenlemek için bir görsel seç</h3>
          <p>Aşağıya sürükle veya bir örnek seç. Sonra maskelemek istediğin alanı fırçayla boya.</p>
          <RefDropZone value={null} onChange={(v) => dispatch({ type: 'setRef', value: v })} />
        </div>
      </div>
    );
  }

  return (
    <div className="ai-inpaint">
      <div className="ai-inpaint-toolbar">
        <div className="ai-tool-group">
          <IconButton label="Fırça" side="bottom" active><IconBrush size={16} /></IconButton>
          <IconButton label="Silgi" side="bottom" onClick={() => paintRef.current?.clear()}>
            <IconEraser size={16} />
          </IconButton>
        </div>
        <div className="ai-tool-group ai-tool-slider">
          <span className="ai-tool-lbl">Fırça</span>
          <Slider value={brush} min={8} max={120} step={1} onChange={setBrush}
                  fmt={(v) => `${v}px`} />
        </div>
        <div className="ai-tool-group">
          <IconButton label="Tüm maskeyi temizle" side="bottom" onClick={() => paintRef.current?.clear()}>
            <IconUndo size={16} />
          </IconButton>
        </div>
        <div className="ai-tool-spacer" />
        <span className="ai-tool-hint">{dirty ? 'Maskelendi · prompt’u yaz' : 'Düzenlenecek alanı boya'}</span>
      </div>

      <div className="ai-inpaint-canvas-wrap">
        {state.generating ? (
          <GeneratingStage progress={state.progress} eta={state.eta} batch={1}
            aspect={state.aspect} prompt={state.prompt}
            onCancel={() => dispatch({ type: 'cancel' })} />
        ) : currentResults.length ? (
          <ResultsGrid results={currentResults.slice(0, 1)} aspect={state.aspect}
            onOpen={openDetail}
            onFavorite={(id) => dispatch({ type: 'favorite', id })}
            onCopyPrompt={(p) => navigator.clipboard?.writeText(p)}
            onDownload={() => {}} />
        ) : (
          <div className="ai-inpaint-canvas" style={{ aspectRatio: ratio }}>
            {state.refImage.src ? (
              <img src={state.refImage.src} alt="" className="ai-inpaint-img" />
            ) : (
              <GenSVG prompt={state.refImage.prompt} seed={state.refImage.seed}
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} />
            )}
            <PaintCanvas
              width={1024}
              height={Math.round(1024 / ratio)}
              brushSize={brush}
              mode="mask"
              background="transparent"
              onDirty={setDirty}
              paintRef={paintRef}
            />
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Outpaint workspace ───────────────────────────────────────────────────
function OutpaintWorkspace(props) {
  const { state, dispatch, currentResults, openDetail } = props;
  const [sides, setSides] = useState({ top: true, right: true, bottom: true, left: true });
  const [expand, setExpand] = useState(40); // px shown around image

  if (!state.refImage) {
    return (
      <div className="ai-mode-empty">
        <div className="ai-mode-empty-inner">
          <h3>Genişletilecek görseli seç</h3>
          <p>Aşağıya bir görsel sürükle. Sonra hangi yönlerde genişletmek istediğini seç.</p>
          <RefDropZone value={null} onChange={(v) => dispatch({ type: 'setRef', value: v })} />
        </div>
      </div>
    );
  }

  const ratio = aspectRatio(state.aspect);
  const toggleSide = (k) => setSides((s) => ({ ...s, [k]: !s[k] }));

  return (
    <div className="ai-outpaint">
      <div className="ai-outpaint-toolbar">
        <div className="ai-tool-group">
          {[
            { k: 'top', l: 'Üst' },
            { k: 'right', l: 'Sağ' },
            { k: 'bottom', l: 'Alt' },
            { k: 'left', l: 'Sol' },
          ].map((s) => (
            <button key={s.k}
              className={`ai-toggle-chip ${sides[s.k] ? 'is-active' : ''}`}
              onClick={() => toggleSide(s.k)}>
              {s.l}
            </button>
          ))}
        </div>
        <div className="ai-tool-group ai-tool-slider">
          <span className="ai-tool-lbl">Genişleme</span>
          <Slider value={expand} min={10} max={120} step={1} onChange={setExpand}
                  fmt={(v) => `${v}%`} />
        </div>
        <div className="ai-tool-spacer" />
        <span className="ai-tool-hint">Yeni alanları doldurmak için prompt yaz</span>
      </div>

      <div className="ai-outpaint-stage">
        {state.generating ? (
          <GeneratingStage progress={state.progress} eta={state.eta} batch={1}
            aspect={state.aspect} prompt={state.prompt}
            onCancel={() => dispatch({ type: 'cancel' })} />
        ) : currentResults.length ? (
          <ResultsGrid results={currentResults.slice(0, 1)} aspect={state.aspect}
            onOpen={openDetail}
            onFavorite={(id) => dispatch({ type: 'favorite', id })}
            onCopyPrompt={(p) => navigator.clipboard?.writeText(p)}
            onDownload={() => {}} />
        ) : (
          <div className="ai-outpaint-frame"
               style={{
                 paddingTop:    sides.top    ? `${expand}px` : 0,
                 paddingRight:  sides.right  ? `${expand}px` : 0,
                 paddingBottom: sides.bottom ? `${expand}px` : 0,
                 paddingLeft:   sides.left   ? `${expand}px` : 0,
               }}>
            <div className="ai-outpaint-glow" />
            <div className="ai-outpaint-core" style={{ aspectRatio: ratio }}>
              {state.refImage.src ? (
                <img src={state.refImage.src} alt="" />
              ) : (
                <GenSVG prompt={state.refImage.prompt} seed={state.refImage.seed}
                        style={{ width: '100%', height: '100%', display: 'block' }} />
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Variations workspace ─────────────────────────────────────────────────
function VariationsWorkspace(props) {
  const { state, dispatch, currentResults, openDetail } = props;
  if (!state.refImage) {
    return (
      <div className="ai-mode-empty">
        <div className="ai-mode-empty-inner">
          <h3>Bir kaynak görsel seç</h3>
          <p>Modelimiz bu görselin temasına 4 farklı varyasyon türetecek.</p>
          <RefDropZone value={null} onChange={(v) => dispatch({ type: 'setRef', value: v })} />
        </div>
      </div>
    );
  }
  const ratio = aspectRatio(state.aspect);
  return (
    <div className="ai-variations">
      <div className="ai-variations-source">
        <div className="ai-i2i-label">Kaynak</div>
        <div className="ai-variations-source-card" style={{ aspectRatio: ratio }}>
          {state.refImage.src ? (
            <img src={state.refImage.src} alt="" />
          ) : (
            <GenSVG prompt={state.refImage.prompt} seed={state.refImage.seed}
                    style={{ width: '100%', height: '100%', display: 'block' }} />
          )}
          <button className="ai-variations-source-x" onClick={() => dispatch({ type: 'setRef', value: null })}>
            <IconClose size={14} />
          </button>
        </div>
      </div>
      <div className="ai-variations-out">
        <div className="ai-i2i-label">Varyasyonlar</div>
        {state.generating ? (
          <GeneratingStage progress={state.progress} eta={state.eta} batch={4}
            aspect={state.aspect} prompt={state.prompt}
            onCancel={() => dispatch({ type: 'cancel' })} />
        ) : currentResults.length ? (
          <div className={`ai-results count-4`}>
            {currentResults.slice(0, 4).map((r) => (
              <ResultCard key={r.id} result={r}
                onOpen={openDetail}
                onFavorite={(id) => dispatch({ type: 'favorite', id })}
                onCopyPrompt={(p) => navigator.clipboard?.writeText(p)}
                onDownload={() => {}} />
            ))}
          </div>
        ) : (
          <div className="ai-variations-empty">
            Prompt'u istersen güncelle, sonra ⏎ ile 4 varyasyon türet.
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Sketch workspace ─────────────────────────────────────────────────────
function SketchWorkspace(props) {
  const { state, dispatch, currentResults, openDetail } = props;
  const [brush, setBrush] = useState(8);
  const paintRef = useRef(null);
  const ratio = aspectRatio(state.aspect);

  return (
    <div className="ai-sketch">
      <div className="ai-inpaint-toolbar">
        <div className="ai-tool-group">
          <IconButton label="Kalem" side="bottom" active><IconBrush size={16} /></IconButton>
          <IconButton label="Temizle" side="bottom" onClick={() => paintRef.current?.clear()}>
            <IconEraser size={16} />
          </IconButton>
        </div>
        <div className="ai-tool-group ai-tool-slider">
          <span className="ai-tool-lbl">Kalem</span>
          <Slider value={brush} min={2} max={28} step={1} onChange={setBrush}
                  fmt={(v) => `${v}px`} />
        </div>
        <div className="ai-tool-spacer" />
        <span className="ai-tool-hint">Bir şeyler çiz ve prompt’unla başlat</span>
      </div>

      <div className="ai-sketch-stage">
        {state.generating ? (
          <GeneratingStage progress={state.progress} eta={state.eta} batch={state.batch}
            aspect={state.aspect} prompt={state.prompt}
            onCancel={() => dispatch({ type: 'cancel' })} />
        ) : currentResults.length ? (
          <ResultsGrid results={currentResults} aspect={state.aspect}
            onOpen={openDetail}
            onFavorite={(id) => dispatch({ type: 'favorite', id })}
            onCopyPrompt={(p) => navigator.clipboard?.writeText(p)}
            onDownload={() => {}} />
        ) : (
          <div className="ai-sketch-canvas" style={{ aspectRatio: ratio }}>
            <PaintCanvas
              width={1024}
              height={Math.round(1024 / ratio)}
              brushSize={brush}
              mode="sketch"
              background="#ffffff"
              paintRef={paintRef}
            />
          </div>
        )}
      </div>
    </div>
  );
}

const WORKSPACES = {
  t2i: T2IWorkspace,
  i2i: I2IWorkspace,
  inpaint: InpaintWorkspace,
  outpaint: OutpaintWorkspace,
  variations: VariationsWorkspace,
  sketch: SketchWorkspace,
};

Object.assign(window, { WORKSPACES, ResultCard });
