// Ideas / Backlog. Three input methods at top + chronological list + filter chips.
const { useState: useStateId, useEffect: useEffectId, useRef: useRefId } = React;

function Ideas({ data, setData, onUseForGen }) {
  const { Button, IconButton, Card, Pill, Textarea, TextInput, SectionHead, EmptyState } = window.UI;
  const I = window.Icons;

  const [text, setText] = useStateId('');
  const [link, setLink] = useStateId('');
  const [recording, setRecording] = useStateId(false);
  const [recTime, setRecTime] = useStateId(0);
  const [filter, setFilter] = useStateId('all');

  useEffectId(() => {
    if (!recording) return;
    const t = setInterval(() => setRecTime(v => v + 1), 1000);
    return () => clearInterval(t);
  }, [recording]);

  const addIdea = (idea) => {
    setData({ ...data, ideas: [{ ...idea, id: 'i' + Date.now(), when: 'только что' }, ...data.ideas] });
  };

  const list = filter === 'all' ? data.ideas : data.ideas.filter(i => i.type === filter);

  const TYPE_ICONS = { text: I.Text, link: I.Link, voice: I.Mic };
  const TYPE_LABELS = { text: 'Текст', link: 'Ссылка', voice: 'Голос' };

  return (
    <div className="max-w-[1100px] mx-auto px-5 sm:px-8 py-8">
      <SectionHead
        kicker="идеи · бэклог"
        title="Что хочется рассказать"
        sub="Закидывайте темы как удобно — текстом, ссылкой или голосом. Потом превратим в карусели."
      />

      {/* Three input methods */}
      <div className="grid md:grid-cols-3 gap-3 mb-8">
        {/* Text */}
        <div className="rounded-2xl border border-ink-200 bg-sky-soft/45 p-4 flex flex-col shadow-soft">
          <div className="flex items-center gap-2 mb-2">
            <span className="h-7 w-7 rounded-lg bg-sky-soft text-sky-ink flex items-center justify-center"><I.Text size={14}/></span>
            <span className="text-[13px] font-semibold">Текст</span>
          </div>
          <Textarea value={text} onChange={setText} placeholder="Сюжет, тезис, шутка — что угодно…" rows={3}/>
          <div className="mt-2">
            <Button size="sm" full disabled={!text.trim()} onClick={() => { addIdea({ type: 'text', preview: text.trim() }); setText(''); }}>Сохранить</Button>
          </div>
        </div>

        {/* Link */}
        <div className="rounded-2xl border border-ink-200 bg-mint-soft/45 p-4 flex flex-col shadow-soft">
          <div className="flex items-center gap-2 mb-2">
            <span className="h-7 w-7 rounded-lg bg-mint-soft text-mint-ink flex items-center justify-center"><I.Link size={14}/></span>
            <span className="text-[13px] font-semibold">Ссылка</span>
          </div>
          <TextInput value={link} onChange={setLink} placeholder="https://…" icon={<I.Link size={14}/>} className="mb-2"/>
          <div className="text-[11.5px] text-ink-500 mb-2 px-1">Мы вытащим заголовок и описание.</div>
          <div className="mt-auto">
            <Button size="sm" full disabled={!link.trim()} onClick={() => { addIdea({ type: 'link', preview: link.trim() }); setLink(''); }}>Сохранить</Button>
          </div>
        </div>

        {/* Voice */}
        <div className="rounded-2xl border border-ink-200 bg-peach-soft/45 p-4 flex flex-col shadow-soft">
          <div className="flex items-center gap-2 mb-2">
            <span className="h-7 w-7 rounded-lg bg-peach-soft text-peach-ink flex items-center justify-center"><I.Mic size={14}/></span>
            <span className="text-[13px] font-semibold">Голосовое</span>
          </div>
          <div className={'flex-1 rounded-xl border ' + (recording ? 'border-red-300 bg-red-50' : 'border-ink-200 bg-ink-50') + ' p-3 flex items-center gap-3'}>
            <button
              onClick={() => { setRecording(v => !v); if (recording && recTime > 0) { addIdea({ type: 'voice', preview: `${Math.floor(recTime/60)}:${String(recTime%60).padStart(2,'0')} — голосовая заметка` }); setRecTime(0); } }}
              className={'h-10 w-10 rounded-full flex items-center justify-center shrink-0 ' + (recording ? 'bg-red-500 text-white animate-pulse' : 'bg-ink-900 text-white')}
            >
              {recording ? <I.Square size={14}/> : <I.Mic size={16}/>}
            </button>
            <div className="flex-1">
              {recording ? (
                <>
                  <div className="flex items-end gap-[2px] h-7">
                    {Array.from({ length: 22 }).map((_, i) => (
                      <span key={i} className="wave-bar w-[3px] rounded-full bg-red-500" style={{ height: '100%', animationDelay: `${(i % 7) * 90}ms`, animationDuration: `${800 + (i % 5)*120}ms` }}/>
                    ))}
                  </div>
                  <div className="text-[12px] font-mono text-red-600 mt-1 tabular-nums">{Math.floor(recTime/60)}:{String(recTime%60).padStart(2,'0')} · идёт запись</div>
                </>
              ) : (
                <>
                  <div className="text-[12.5px] text-ink-700">Нажмите, чтобы записать</div>
                  <div className="text-[11px] text-ink-500">До 5 минут. Расшифруем автоматом.</div>
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Filter chips */}
      <div className="flex items-center gap-2 mb-5 overflow-x-auto no-scrollbar">
        {[
          { v: 'all', label: 'Все', count: data.ideas.length },
          { v: 'text', label: 'Текст', count: data.ideas.filter(i => i.type === 'text').length },
          { v: 'link', label: 'Ссылки', count: data.ideas.filter(i => i.type === 'link').length },
          { v: 'voice', label: 'Голос', count: data.ideas.filter(i => i.type === 'voice').length },
        ].map((f) => (
          <Pill key={f.v} active={filter === f.v} onClick={() => setFilter(f.v)}>
            {f.label} <span className="text-[11px] opacity-60 tabular-nums">{f.count}</span>
          </Pill>
        ))}
      </div>

      {/* List */}
      {list.length === 0 ? (
        <EmptyState
          icon={<I.Lightbulb size={22}/>}
          title="Пока пусто"
          sub="Закиньте первую идею выше — текстом, ссылкой или голосом."
        />
      ) : (
        <Card className="overflow-hidden">
          {list.map((idea, i) => {
            const Icon = TYPE_ICONS[idea.type];
            return (
              <div key={idea.id} className={'flex items-center gap-3 px-4 sm:px-5 py-3.5 ' + (i > 0 ? 'border-t border-ink-200' : '')}>
                <div className="h-9 w-9 rounded-lg bg-ink-100 flex items-center justify-center text-ink-700 shrink-0"><Icon size={14}/></div>
                <div className="flex-1 min-w-0">
                  <div className="text-[13.5px] truncate">{idea.preview}</div>
                  <div className="text-[11.5px] text-ink-500 mt-0.5">{TYPE_LABELS[idea.type]} · {idea.when}</div>
                </div>
                <div className="flex items-center gap-1.5">
                  <Button size="sm" variant="outline" icon={<I.Sparkles size={13}/>} onClick={() => onUseForGen(idea)}>Использовать</Button>
                  <IconButton size="sm" onClick={() => setData({ ...data, ideas: data.ideas.filter(x => x.id !== idea.id) })}><I.Trash size={14}/></IconButton>
                </div>
              </div>
            );
          })}
        </Card>
      )}
    </div>
  );
}

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