const { useState, useEffect, useRef } = React;

const api = {
  get: async (u) => { const r = await fetch(u); return r.json(); },
  post: async (u, d) => { const r = await fetch(u, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(d||{}) }); return r.json(); },
  put: async (u, d) => { const r = await fetch(u, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(d||{}) }); return r.json(); },
  del: async (u) => { const r = await fetch(u, { method:'DELETE' }); return r.json(); },
};

const STEPS = [
  { n:1, icon:'🔍', label:'Marktforschung', short:'Markt' },
  { n:2, icon:'🎯', label:'Positionierung', short:'Position' },
  { n:3, icon:'📋', label:'Konzept & Struktur', short:'Konzept' },
  { n:4, icon:'🏆', label:'Verleger-Feedback', short:'Feedback' },
];

// ===== MARKT-DASHBOARD =====
function MarketDashboard({ projectId, analysis, onRefresh }) {
  const [genre, setGenre] = useState('');
  const [loading, setLoading] = useState(false);

  async function runAnalysis() {
    setLoading(true);
    await api.post(`/api/projects/${projectId}/market-analysis`, { genre });
    onRefresh && onRefresh();
    setLoading(false);
  }

  if (!analysis) return (
    <div className="bg-white rounded-xl border p-6 space-y-4">
      <h3 className="font-bold text-lg">📊 Marktanalyse-Dashboard</h3>
      <p className="text-sm text-gray-500">Lassen Sie die KI aktuelle Markttrends, Mitbewerber und Marktlücken analysieren.</p>
      <div>
        <label className="block text-xs text-gray-500 mb-1">Genre / Bereich (optional)</label>
        <input type="text" value={genre} onChange={e => setGenre(e.target.value)}
          placeholder="z.B. Krimi, Sachbuch, Ratgeber..." className="w-full border rounded px-3 py-2 text-sm" />
      </div>
      <button onClick={runAnalysis} disabled={loading}
        className="w-full py-3 rounded text-white font-bold disabled:opacity-50"
        style={{background:'#2D5016'}}>
        {loading ? '⏳ Analysiere Markt...' : '🔍 Marktanalyse starten'}
      </button>
    </div>
  );

  const trends = JSON.parse(typeof analysis.trends === 'string' ? analysis.trends : JSON.stringify(analysis.trends || []));
  const opportunities = JSON.parse(typeof analysis.opportunities === 'string' ? analysis.opportunities : JSON.stringify(analysis.opportunities || []));
  const recommendations = JSON.parse(typeof analysis.recommendations === 'string' ? analysis.recommendations : JSON.stringify(analysis.recommendations || []));
  const competitors = JSON.parse(typeof analysis.competitors === 'string' ? analysis.competitors : JSON.stringify(analysis.competitors || []));

  return (
    <div className="space-y-4">
      {/* Trends */}
      <div className="bg-white rounded-xl border p-4">
        <h4 className="font-bold mb-3">📈 Aktuelle Markttrends</h4>
        <div className="space-y-2">
          {trends.map((t, i) => (
            <div key={i} className="flex items-start gap-3 p-2 bg-gray-50 rounded">
              <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${t.potential==='hoch'?'bg-green-100 text-green-700':t.potential==='mittel'?'bg-yellow-100 text-yellow-700':'bg-red-100 text-red-600'}`}>
                {t.potential}
              </span>
              <div>
                <p className="font-semibold text-sm">{t.name}</p>
                <p className="text-xs text-gray-500">{t.description}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Marktlücken */}
      <div className="bg-white rounded-xl border p-4">
        <h4 className="font-bold mb-3">💡 Marktlücken & Chancen</h4>
        <div className="space-y-2">
          {opportunities.map((o, i) => (
            <div key={i} className="flex items-center gap-2 p-2 bg-green-50 rounded text-sm">
              <span className="text-green-600">✓</span> {o}
            </div>
          ))}
        </div>
      </div>

      {/* 3 Buchideen */}
      <div className="bg-white rounded-xl border p-4">
        <h4 className="font-bold mb-3">🚀 Empfohlene Buchideen</h4>
        <div className="space-y-3">
          {recommendations.map((r, i) => (
            <div key={i} className="p-3 border rounded-lg" style={{borderLeft:'4px solid #2D5016'}}>
              <p className="font-bold" style={{color:'#2D5016'}}>#{i+1} {r.title}</p>
              <p className="text-sm text-gray-600 mt-1">{r.description}</p>
              <div className="flex gap-4 mt-2 text-xs text-gray-500">
                <span>👥 {r.targetAudience}</span>
              </div>
              <p className="text-xs text-green-700 mt-1">💡 {r.rationale}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Mitbewerber */}
      {competitors.length > 0 && (
        <div className="bg-white rounded-xl border p-4">
          <h4 className="font-bold mb-3">🔎 Mitbewerber-Analyse</h4>
          <div className="space-y-2">
            {competitors.map((c, i) => (
              <div key={i} className="p-2 bg-gray-50 rounded text-sm">
                <p className="font-semibold">„{c.title}" – {c.author}</p>
                <p className="text-green-700 text-xs">✓ {c.strength}</p>
                <p className="text-red-600 text-xs">✗ {c.weakness}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      <button onClick={runAnalysis} disabled={loading}
        className="w-full py-2 border rounded text-sm hover:bg-gray-50">
        {loading ? '⏳' : '🔄 Analyse aktualisieren'}
      </button>
    </div>
  );
}

// ===== KI-TOGGLE =====
function AiToggle({ projectId, provider, model, ollamaModels, onSave }) {
  const [p, setP] = useState(provider || 'claude');
  const [m, setM] = useState(model || 'mixtral:latest');

  async function save(newP, newM) {
    setP(newP); setM(newM);
    await api.put(`/api/projects/${projectId}/ai`, { provider: newP, model: newM });
    onSave && onSave(newP, newM);
  }

  return (
    <div className="bg-white rounded-xl border p-4 space-y-3">
      <h4 className="font-bold text-sm">🤖 KI-Auswahl</h4>
      <div className="flex gap-2">
        <button onClick={() => save('claude', 'claude-sonnet-4')}
          className={`flex-1 py-2 px-3 rounded text-sm font-semibold transition ${p==='claude'?'text-white':'border hover:bg-gray-50 text-gray-600'}`}
          style={p==='claude'?{background:'#2D5016'}:{}}>
          ☁️ Claude API
          <span className="block text-xs font-normal opacity-75">Beste Qualität</span>
        </button>
        <button onClick={() => save('ollama', m)}
          className={`flex-1 py-2 px-3 rounded text-sm font-semibold transition ${p==='ollama'?'text-white':'border hover:bg-gray-50 text-gray-600'}`}
          style={p==='ollama'?{background:'#1a5276'}:{}}>
          🖥️ Ollama lokal
          <span className="block text-xs font-normal opacity-75">Kostenlos</span>
        </button>
      </div>
      {p === 'ollama' && ollamaModels.length > 0 && (
        <select value={m} onChange={e => save('ollama', e.target.value)} className="w-full border rounded px-3 py-2 text-sm">
          {ollamaModels.map(om => <option key={om} value={om}>{om}</option>)}
        </select>
      )}
      {p === 'claude' && <p className="text-xs text-green-700 p-2 bg-green-50 rounded">✅ Claude Sonnet 4 · ~0.02€/Anfrage</p>}
    </div>
  );
}

// ===== CHAT =====
function ChatArea({ projectId, step, provider, ollamaModel }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const endRef = useRef(null);

  useEffect(() => { loadMsgs(); }, [projectId]);
  useEffect(() => { endRef.current?.scrollIntoView({ behavior:'smooth' }); }, [messages]);

  async function loadMsgs() {
    const msgs = await api.get(`/api/projects/${projectId}/messages`);
    setMessages(msgs);
  }

  async function send() {
    if (!input.trim() || sending) return;
    const text = input.trim();
    setInput('');
    setSending(true);
    const temp = { id:'tmp', role:'user', content:text };
    setMessages(prev => [...prev, temp]);
    const r = await api.post(`/api/projects/${projectId}/chat`, { message: text });
    if (r.error) { alert(r.error); setMessages(prev => prev.filter(m=>m.id!=='tmp')); }
    else setMessages(prev => [...prev.filter(m=>m.id!=='tmp'), temp, { id:r.msgId, role:'assistant', content:r.message }]);
    setSending(false);
  }

  function renderMd(text) {
    return text
      .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
      .replace(/^#{1,3}\s+(.+)$/gm, '<strong style="color:#2D5016">$1</strong>')
      .replace(/^[-*]\s+(.+)$/gm, '<div style="margin-left:12px">• $1</div>')
      .replace(/\n\n/g, '<br><br>')
      .replace(/\n/g, '<br>');
  }

  const QUICK = ['Schritt abschließen', 'Fasse bisher zusammen', 'Was ist der nächste Schritt?', 'Welche Risiken sehe ich?', 'Kritisches Feedback bitte'];

  return (
    <div className="flex flex-col" style={{height:'calc(100vh - 280px)'}}>
      <div className="flex-1 overflow-y-auto space-y-3 mb-3 pr-1">
        {messages.map((m,i) => (
          <div key={m.id||i} className={`flex ${m.role==='user'?'justify-end':'justify-start'}`}>
            {m.role==='assistant' && <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold mr-2 mt-1 flex-shrink-0" style={{background:'#2D5016'}}>V</div>}
            <div className={`max-w-2xl px-4 py-3 text-sm ${m.role==='user'?'msg-user':'msg-ai'}`}
              dangerouslySetInnerHTML={m.role==='assistant' ? {__html:renderMd(m.content)} : undefined}>
              {m.role==='user' ? m.content : null}
            </div>
          </div>
        ))}
        {sending && (
          <div className="flex justify-start">
            <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs mr-2" style={{background:'#2D5016'}}>V</div>
            <div className="msg-ai px-4 py-3 text-sm text-gray-400 animate-pulse">✍️ Ihr Verleger denkt nach...</div>
          </div>
        )}
        <div ref={endRef} />
      </div>

      <div className="flex gap-2 mb-2">
        <textarea value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send();} }}
          placeholder="Ihre Nachricht... (Enter = senden)"
          rows={2} className="flex-1 border rounded px-3 py-2 text-sm resize-none" disabled={sending} />
        <button onClick={send} disabled={sending||!input.trim()}
          className="px-4 rounded text-white disabled:opacity-50 self-end py-2"
          style={{background:'#2D5016'}}>Senden</button>
      </div>
      <div className="flex gap-1 flex-wrap">
        {QUICK.map(q => (
          <button key={q} onClick={() => setInput(q)}
            className="text-xs px-2 py-1 border rounded hover:bg-gray-50 text-gray-600">{q}</button>
        ))}
      </div>
    </div>
  );
}

// ===== PROJEKT-DETAIL =====
function ProjectDetail({ project, onBack, ollamaModels }) {
  const [step, setStep] = useState(project.step || 1);
  const [view, setView] = useState('chat'); // chat | market
  const [analysis, setAnalysis] = useState(null);
  const [provider, setProvider] = useState(project.ai_provider || 'claude');
  const [model, setModel] = useState(project.ai_model || 'claude-sonnet-4');

  useEffect(() => {
    if (project.market_analysis) {
      try { setAnalysis(JSON.parse(project.market_analysis)); } catch {}
    }
  }, [project]);

  async function changeStep(n) {
    await api.put(`/api/projects/${project.id}/step`, { step: n });
    setStep(n);
  }

  async function exportDocx() {
    const r = await fetch(`/api/projects/${project.id}/export`);
    const blob = await r.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href=url; a.download=`Buchkonzept_${project.title}.docx`; a.click();
    URL.revokeObjectURL(url);
  }

  async function loadAnalysis() {
    const p = await api.get(`/api/projects/${project.id}`);
    if (p.market_analysis) try { setAnalysis(JSON.parse(p.market_analysis)); } catch {}
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="text-white p-4" style={{background:'#2D5016'}}>
        <div className="flex items-center justify-between max-w-6xl mx-auto">
          <div className="flex items-center gap-3">
            <button onClick={onBack} className="text-white opacity-75 hover:opacity-100">← Projekte</button>
            <div>
              <h2 className="font-bold">{project.title}</h2>
              <p className="text-xs opacity-75">Schritt {step}/4</p>
            </div>
          </div>
          <div className="flex gap-2">
            <button onClick={() => setView(view==='chat'?'market':'chat')}
              className="px-3 py-1 bg-white bg-opacity-20 rounded text-sm">
              {view==='chat'?'📊 Markt':'💬 Chat'}
            </button>
            <button onClick={exportDocx} className="px-3 py-1 bg-white bg-opacity-20 rounded text-sm">📥 Export</button>
          </div>
        </div>
      </div>

      {/* Schritte-Navigation */}
      <div className="bg-white border-b px-4 py-3">
        <div className="flex gap-2 max-w-6xl mx-auto overflow-x-auto">
          {STEPS.map(s => (
            <button key={s.n} onClick={() => changeStep(s.n)}
              className={`px-3 py-1.5 rounded text-xs font-semibold whitespace-nowrap transition ${step===s.n?'step-active':s.n<step?'step-done':'step-todo'}`}>
              {s.icon} {s.short}
            </button>
          ))}
        </div>
      </div>

      <div className="max-w-6xl mx-auto p-4 grid md:grid-cols-3 gap-4">
        {/* Linke Sidebar */}
        <div className="space-y-4">
          <AiToggle projectId={project.id} provider={provider} model={model} ollamaModels={ollamaModels}
            onSave={(p,m) => { setProvider(p); setModel(m); }} />

          {/* Schritt-Info */}
          <div className="bg-white rounded-xl border p-4">
            <h4 className="font-bold text-sm mb-2" style={{color:'#2D5016'}}>
              {STEPS[step-1]?.icon} {STEPS[step-1]?.label}
            </h4>
            <p className="text-xs text-gray-500">
              {step===1 && 'Markttrends analysieren, Zielgruppe definieren, 3 Buchideen entwickeln.'}
              {step===2 && 'Format, Zielgruppe, Umfang und Alleinstellungsmerkmal festlegen.'}
              {step===3 && 'Detailliertes Inhaltsverzeichnis und Konzept entwickeln.'}
              {step===4 && 'Kritische Prüfung: Was könnte floppen? Was ist der echte USP?'}
            </p>
          </div>
        </div>

        {/* Hauptbereich */}
        <div className="md:col-span-2">
          {view === 'market' ? (
            <MarketDashboard projectId={project.id} analysis={analysis} onRefresh={loadAnalysis} />
          ) : (
            <div className="bg-white rounded-xl border p-4">
              <ChatArea projectId={project.id} step={step} provider={provider} ollamaModel={model} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ===== PROJEKTLISTE =====
function ProjectList({ onSelect }) {
  const [projects, setProjects] = useState([]);
  const [newTitle, setNewTitle] = useState('');

  useEffect(() => { api.get('/api/projects').then(setProjects); }, []);

  async function create() {
    if (!newTitle.trim()) return;
    const r = await api.post('/api/projects', { title: newTitle.trim() });
    setNewTitle('');
    const updated = await api.get('/api/projects');
    setProjects(updated);
    onSelect(updated.find(p => p.id === r.id));
  }

  return (
    <div className="max-w-3xl mx-auto p-6 space-y-6">
      <div className="bg-white rounded-xl border p-5">
        <h2 className="font-bold text-lg mb-3">📚 Neues Buchprojekt</h2>
        <div className="flex gap-3">
          <input type="text" value={newTitle} onChange={e => setNewTitle(e.target.value)}
            onKeyDown={e => e.key==='Enter' && create()}
            placeholder="Projekttitel (z.B. Mein Krimi-Roman)" className="flex-1 border rounded px-3 py-2" />
          <button onClick={create} className="px-5 py-2 rounded text-white font-bold" style={{background:'#2D5016'}}>
            + Starten
          </button>
        </div>
      </div>

      <div className="space-y-3">
        {projects.map(p => (
          <div key={p.id} onClick={() => onSelect(p)}
            className="bg-white rounded-xl border p-4 cursor-pointer hover:shadow-md transition">
            <div className="flex justify-between items-start">
              <div>
                <h3 className="font-bold">{p.title}</h3>
                <p className="text-xs text-gray-400 mt-0.5">{p.updated_at?.substring(0,10)}</p>
              </div>
              <span className="text-xs px-2 py-1 rounded-full bg-green-100 text-green-700">
                {STEPS[((p.step||1)-1)]?.icon} Schritt {p.step||1}/4
              </span>
            </div>
            <div className="mt-2 bg-gray-100 rounded-full h-1.5">
              <div className="h-1.5 rounded-full" style={{width:`${((p.step||1)/4)*100}%`, background:'#2D5016'}}></div>
            </div>
          </div>
        ))}
        {projects.length === 0 && (
          <div className="text-center py-12 text-gray-400">
            <p className="text-5xl mb-4">📖</p>
            <p>Noch kein Projekt. Starte jetzt mit deiner ersten Buchidee!</p>
          </div>
        )}
      </div>
    </div>
  );
}

// ===== HAUPT-APP =====
function App() {
  const [currentProject, setCurrentProject] = useState(null);
  const [health, setHealth] = useState({ ollama: false, claudeKey: false, models: [] });

  useEffect(() => {
    api.get('/api/health').then(setHealth).catch(() => {});
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      {!currentProject && (
        <header className="text-white p-4 shadow" style={{background:'#2D5016'}}>
          <div className="max-w-3xl mx-auto flex items-center justify-between">
            <div>
              <h1 className="text-xl font-bold">📚 BookCoach</h1>
              <p className="text-xs opacity-75">Ihr persönlicher Buchverleger & Marktanalyst</p>
            </div>
            <div className="flex gap-2 text-xs">
              <span className={`px-2 py-1 rounded ${health.claudeKey?'bg-green-700':'bg-red-700'}`}>
                {health.claudeKey?'☁️ Claude':'☁️ Kein Key'}
              </span>
              <span className={`px-2 py-1 rounded ${health.ollama?'bg-green-700':'bg-gray-600'}`}>
                {health.ollama?'🖥️ Ollama':'🖥️ Offline'}
              </span>
            </div>
          </div>
        </header>
      )}

      {currentProject ? (
        <ProjectDetail
          project={currentProject}
          onBack={() => setCurrentProject(null)}
          ollamaModels={health.models || []}
        />
      ) : (
        <ProjectList onSelect={setCurrentProject} />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
