// Carousel preview + edit. Phone frame on left, slide list on right, edit mode.
const { useState: useStateP, useRef: useRefP } = React;

const SLIDE_KINDS = [
  { id: 'cover',  name: 'Обложка', icon: 'Cover' },
  { id: 'header', name: 'Заголовок', icon: 'Type' },
  { id: 'number', name: 'Цифра', icon: 'Number' },
  { id: 'quote',  name: 'Цитата', icon: 'Quote' },
  { id: 'body',   name: 'Текст', icon: 'Stack' },
];

function Preview({ org, slides, setSlides, onBack, onSaved }) {
  const { Button, IconButton, Card, Pill, Modal } = window.UI;
  const I = window.Icons;
  const { SlideFrame } = window.Carousel;

  const [active, setActive] = useStateP(0);
  const [editing, setEditing] = useStateP(false);
  const [tgOpen, setTgOpen] = useStateP(false);
  const [downloadOpen, setDownloadOpen] = useStateP(false);
  const [savedTip, setSavedTip] = useStateP(false);

  const slide = slides[active];

  const updateSlide = (patch) => {
    setSlides(slides.map((s, i) => i === active ? { ...s, ...patch } : s));
  };
  const regenerateOne = () => {
    // Mock: shuffle small details to feel "regenerated"
    setSlides(slides.map((s, i) => i === active ? { ...s, body: s.body ? s.body + ' ' : s.body, label: s.label } : s));
  };

  return (
    <div className="max-w-[1400px] mx-auto px-4 sm:px-8 py-6 fade-in">
      {/* Top actions */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-5">
        <div className="flex items-center gap-3 min-w-0">
          <IconButton onClick={onBack} variant="outline" size="sm"><I.ChevronLeft size={16}/></IconButton>
          <div className="min-w-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-ink-500">превью</div>
            <div className="text-[18px] sm:text-[20px] font-semibold tracking-tight truncate">{slides[0].title}</div>
          </div>
        </div>
        <div className="flex items-center gap-1.5">
          <Button variant="outline" size="sm" icon={<I.Save size={14}/>} onClick={() => { onSaved(); setSavedTip(true); setTimeout(() => setSavedTip(false), 1800); }}>Сохранить черновик</Button>
          <Button variant="outline" size="sm" icon={<I.Telegram size={14}/>} onClick={() => setTgOpen(true)}>В Telegram</Button>
          <Button size="sm" icon={<I.Download size={14}/>} onClick={() => setDownloadOpen(true)}>Скачать ZIP</Button>
        </div>
      </div>

      {savedTip && (
        <div className="fixed bottom-6 right-6 bg-ink-900 text-white px-4 py-2 rounded-full text-[12.5px] shadow-pop slide-up z-40 flex items-center gap-2">
          <I.Check size={14} strokeWidth={2.5}/> Черновик сохранён
        </div>
      )}

      <div className="grid lg:grid-cols-[1fr_360px] gap-6">
        {/* Phone preview */}
        <div className="bg-paper border border-ink-200 rounded-3xl p-6 sm:p-10 flex flex-col items-center">
          <PhoneFrame>
            <div className="relative w-full h-full overflow-hidden">
              {slides.map((s, i) => (
                <div
                  key={s.id}
                  className="absolute inset-0 transition-transform duration-500 ease-[cubic-bezier(.2,.8,.2,1)]"
                  style={{ transform: `translateX(${(i - active) * 100}%)` }}
                >
                  <SlideFrame slide={s} brand={org.brand} scale={0.62}/>
                </div>
              ))}

              {/* nav arrows */}
              <button
                onClick={() => setActive(Math.max(0, active - 1))}
                disabled={active === 0}
                className="absolute left-3 top-1/2 -translate-y-1/2 h-10 w-10 rounded-full bg-white/85 backdrop-blur text-ink-900 flex items-center justify-center shadow-card disabled:opacity-30 hover:bg-white"
              ><I.ChevronLeft size={18}/></button>
              <button
                onClick={() => setActive(Math.min(slides.length - 1, active + 1))}
                disabled={active === slides.length - 1}
                className="absolute right-3 top-1/2 -translate-y-1/2 h-10 w-10 rounded-full bg-white/85 backdrop-blur text-ink-900 flex items-center justify-center shadow-card disabled:opacity-30 hover:bg-white"
              ><I.ChevronRight size={18}/></button>

              {/* dots */}
              <div className="absolute bottom-4 left-0 right-0 flex items-center justify-center gap-1.5">
                {slides.map((_, i) => (
                  <span key={i} className={'rounded-full transition-all ' + (i === active ? 'bg-white h-1.5 w-5' : 'bg-white/45 h-1.5 w-1.5')}/>
                ))}
              </div>
            </div>
          </PhoneFrame>

          <div className="mt-6 flex items-center gap-3">
            <span className="text-[12.5px] font-mono text-ink-500 tabular-nums">{String(active + 1).padStart(2, '0')} / {String(slides.length).padStart(2, '0')}</span>
            <div className="h-1 w-40 sm:w-60 bg-ink-200 rounded-full overflow-hidden">
              <div className="h-full bg-ink-900 transition-all" style={{ width: ((active + 1) / slides.length * 100) + '%' }}/>
            </div>
          </div>
        </div>

        {/* Slide list + editor */}
        <div className="space-y-4">
          {/* Slide thumbnails */}
          <Card className="overflow-hidden">
            <div className="px-4 py-3 border-b border-ink-200 flex items-center justify-between">
              <div className="text-[12px] font-semibold uppercase tracking-[0.14em] text-ink-500">Слайды · {slides.length}</div>
              <button onClick={() => setEditing(!editing)} className={'text-[12px] font-semibold inline-flex items-center gap-1 px-2 h-7 rounded-md ' + (editing ? 'bg-ink-900 text-white' : 'text-ink-700 hover:bg-ink-100')}>
                <I.Edit size={12}/> {editing ? 'Готово' : 'Править'}
              </button>
            </div>
            <div className="max-h-[320px] overflow-y-auto thin-scroll p-2">
              {slides.map((s, i) => (
                <button
                  key={s.id}
                  onClick={() => setActive(i)}
                  className={'w-full flex items-center gap-3 p-2 rounded-xl transition-colors ' + (i === active ? 'bg-ink-50 ring-1 ring-ink-200' : 'hover:bg-ink-50')}
                >
                  <span className="text-[11px] font-mono text-ink-500 tabular-nums w-6 text-right">{String(i + 1).padStart(2, '0')}</span>
                  <div className="rounded-md overflow-hidden ring-1 ring-ink-200 shrink-0" style={{ width: 56, height: 70, background: s.bg }}>
                    <div className="w-full h-full" style={{ transform: 'scale(0.45)', transformOrigin: 'top left', width: 540 * 0.45, height: 675 * 0.45 }}>
                      <window.Carousel.SlideFrame slide={s} brand={org.brand} scale={0.105}/>
                    </div>
                  </div>
                  <div className="flex-1 min-w-0 text-left">
                    <div className="text-[12px] font-semibold uppercase tracking-wide text-ink-500">{SLIDE_KINDS.find(k => k.id === s.kind)?.name}</div>
                    <div className="text-[12.5px] truncate">{s.title || s.body || '—'}</div>
                  </div>
                </button>
              ))}
            </div>
          </Card>

          {/* Edit panel */}
          {editing ? (
            <Card className="p-4 fade-in">
              <div className="text-[12px] font-semibold uppercase tracking-[0.14em] text-ink-500 mb-3">Редактировать слайд {active + 1}</div>

              <div className="text-[11.5px] font-semibold text-ink-500 mb-2">Тип</div>
              <div className="grid grid-cols-5 gap-1.5 mb-4">
                {SLIDE_KINDS.map((k) => {
                  const Icon = I[k.icon];
                  const active2 = slide.kind === k.id;
                  return (
                    <button key={k.id} onClick={() => updateSlide({ kind: k.id })} className={'flex flex-col items-center gap-1 py-2.5 rounded-lg border transition-colors ' + (active2 ? 'border-ink-900 bg-ink-50' : 'border-ink-200 hover:bg-ink-50')}>
                      <Icon size={14}/>
                      <span className="text-[10px] font-medium">{k.name}</span>
                    </button>
                  );
                })}
              </div>

              {(slide.kind === 'cover' || slide.kind === 'header' || slide.kind === 'body') && (
                <FieldText label="Заголовок" value={slide.title || ''} onChange={(v) => updateSlide({ title: v })}/>
              )}
              {slide.kind === 'cover' && (
                <FieldText label="Подзаголовок" value={slide.subtitle || ''} onChange={(v) => updateSlide({ subtitle: v })} multi/>
              )}
              {slide.kind === 'number' && (
                <>
                  <FieldText label="Цифра" value={slide.number || ''} onChange={(v) => updateSlide({ number: v })}/>
                  <FieldText label="Подпись" value={slide.body || ''} onChange={(v) => updateSlide({ body: v })} multi/>
                </>
              )}
              {slide.kind === 'quote' && (
                <>
                  <FieldText label="Цитата" value={slide.body || ''} onChange={(v) => updateSlide({ body: v })} multi/>
                  <FieldText label="Автор" value={slide.author || ''} onChange={(v) => updateSlide({ author: v })}/>
                </>
              )}
              {slide.kind === 'header' && (
                <FieldText label="Текст" value={slide.body || ''} onChange={(v) => updateSlide({ body: v })} multi/>
              )}
              {slide.kind === 'body' && (
                <div className="mb-3">
                  <div className="text-[11.5px] font-semibold text-ink-500 mb-1.5">Пункты</div>
                  <div className="space-y-1.5">
                    {(slide.items || []).map((it, i) => (
                      <div key={i} className="flex items-center gap-2">
                        <input value={it} onChange={(e) => updateSlide({ items: slide.items.map((x, idx) => idx === i ? e.target.value : x) })}
                          className="flex-1 h-9 px-3 rounded-lg border border-ink-200 text-[13px] focus:outline-none focus:border-ink-900"/>
                        <IconButton size="sm" onClick={() => updateSlide({ items: slide.items.filter((_, idx) => idx !== i) })}><I.X size={13}/></IconButton>
                      </div>
                    ))}
                    <Button size="sm" variant="outline" icon={<I.Plus size={13}/>} onClick={() => updateSlide({ items: [...(slide.items || []), 'новый пункт'] })}>Добавить пункт</Button>
                  </div>
                </div>
              )}

              <FieldText label="Подпись (метка)" value={slide.label || ''} onChange={(v) => updateSlide({ label: v })}/>

              <div className="flex items-center gap-2 mt-4">
                <Button size="sm" variant="outline" icon={<I.Refresh size={13}/>} onClick={regenerateOne}>Перегенерировать</Button>
                <Button size="sm" variant="ghost" icon={<I.Trash size={13}/>} onClick={() => {
                  if (slides.length === 1) return;
                  setSlides(slides.filter((_, i) => i !== active));
                  setActive(Math.max(0, active - 1));
                }}>Удалить</Button>
              </div>
            </Card>
          ) : (
            <Card className="p-4">
              <div className="text-[12px] font-semibold uppercase tracking-[0.14em] text-ink-500 mb-3">Сводка</div>
              <ul className="text-[13px] space-y-2 text-ink-700">
                <li className="flex justify-between"><span className="text-ink-500">Слайдов</span><span className="font-semibold tabular-nums">{slides.length}</span></li>
                <li className="flex justify-between"><span className="text-ink-500">Формат</span><span className="font-semibold">1080×1350 · 4:5</span></li>
                <li className="flex justify-between"><span className="text-ink-500">Шрифты</span><span className="font-semibold">{org.brand.fonts.join(' · ')}</span></li>
                <li className="flex justify-between items-center"><span className="text-ink-500">Палитра</span>
                  <div className="flex gap-1">{org.brand.colors.map((c, i) => <span key={i} className="h-4 w-4 rounded-md ring-1 ring-ink-200" style={{ background: c }}/>)}</div>
                </li>
              </ul>
              <div className="mt-4">
                <Button size="sm" full variant="outline" icon={<I.Refresh size={13}/>}>Перегенерировать всё</Button>
              </div>
            </Card>
          )}
        </div>
      </div>

      {/* Download modal */}
      <Modal open={downloadOpen} onClose={() => setDownloadOpen(false)} title="ZIP с PNG-слайдами" sub="Можно загружать прямо в Instagram-карусель.">
        <div className="rounded-2xl border border-ink-200 bg-paper p-5">
          <div className="flex items-center gap-3">
            <div className="h-12 w-12 rounded-xl bg-ink-900 text-white flex items-center justify-center"><I.Download size={18}/></div>
            <div className="flex-1">
              <div className="font-mono text-[13px]">{slides[0].title?.toLowerCase().replace(/[^a-zа-я0-9]+/gi, '-') || 'carousel'}.zip</div>
              <div className="text-[11.5px] text-ink-500">{slides.length} файлов · ~{(slides.length * 0.4).toFixed(1)} МБ</div>
            </div>
          </div>
          <div className="mt-4 flex items-center gap-2">
            <Button onClick={() => setDownloadOpen(false)} icon={<I.Download size={14}/>}>Скачать ZIP</Button>
            <Button variant="ghost" onClick={() => setDownloadOpen(false)}>Отмена</Button>
          </div>
        </div>
      </Modal>

      {/* Telegram modal */}
      <Modal open={tgOpen} onClose={() => setTgOpen(false)} title="Отправить в Telegram" sub="Бот пришлёт все слайды отдельным альбомом в @username">
        <div className="rounded-2xl border border-ink-200 p-5 bg-paper">
          <div className="flex items-center gap-3">
            <div className="h-12 w-12 rounded-xl bg-[#229ED9] text-white flex items-center justify-center"><I.Telegram size={20}/></div>
            <div>
              <div className="text-[13.5px] font-semibold">@omneee_bot</div>
              <div className="text-[12px] text-ink-500">Подключён к этой организации</div>
            </div>
          </div>
        </div>
        <div className="mt-4 flex items-center gap-2">
          <Button onClick={() => setTgOpen(false)} icon={<I.Send size={14}/>}>Отправить</Button>
          <Button variant="ghost" onClick={() => setTgOpen(false)}>Отмена</Button>
        </div>
      </Modal>
    </div>
  );
}

function FieldText({ label, value, onChange, multi = false }) {
  return (
    <div className="mb-3">
      <div className="text-[11.5px] font-semibold text-ink-500 mb-1.5">{label}</div>
      {multi ? (
        <textarea value={value} onChange={(e) => onChange(e.target.value)} rows={3} className="w-full px-3 py-2 rounded-lg border border-ink-200 text-[13px] focus:outline-none focus:border-ink-900 resize-none"/>
      ) : (
        <input value={value} onChange={(e) => onChange(e.target.value)} className="w-full h-9 px-3 rounded-lg border border-ink-200 text-[13px] focus:outline-none focus:border-ink-900"/>
      )}
    </div>
  );
}

function PhoneFrame({ children }) {
  return (
    <div className="phone-shadow" style={{ width: 340, height: 686, borderRadius: 44, padding: 9, background: '#0F0F0F' }}>
      <div className="relative w-full h-full overflow-hidden" style={{ borderRadius: 36, background: 'white' }}>
        {/* notch */}
        <div className="absolute top-1.5 left-1/2 -translate-x-1/2 h-5 w-24 bg-black rounded-full z-10"/>
        {/* status bar */}
        <div className="absolute top-0 left-0 right-0 h-9 flex items-end justify-between px-7 pb-1.5 z-10 text-[11px] font-semibold pointer-events-none">
          <span className="tabular-nums">9:41</span>
          <span className="tabular-nums opacity-80">•••</span>
        </div>
        {/* IG-like top */}
        <div className="absolute top-9 left-0 right-0 h-10 flex items-center justify-between px-4 z-10 bg-white border-b border-ink-100">
          <div className="flex items-center gap-2">
            <div className="h-7 w-7 rounded-full" style={{ background: 'linear-gradient(45deg,#feda75,#fa7e1e,#d62976,#962fbf,#4f5bd5)' }}/>
            <div>
              <div className="text-[11px] font-semibold leading-none">your_brand</div>
              <div className="text-[9px] text-ink-500 leading-none mt-0.5">Спонсорский</div>
            </div>
          </div>
          <div className="text-[14px] tracking-wider">⋯</div>
        </div>
        {/* content area */}
        <div className="absolute inset-x-0 bottom-0" style={{ top: 76 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

window.Screens = window.Screens || {};
window.Screens.Preview = Preview;
