// Chat sidebar + full-page chat for Regula
const ChatSidebar = ({ scope = "Gruppo", company = null, onExpand }) => {
  const [messages, setMessages] = React.useState([
    {
      role: 'ai',
      content: (
        <>
          Ciao Lorenzo. Ho analizzato i dati del gruppo per <strong>aprile 2026</strong>. Due segnali da monitorare:
          <ul style={{ margin: '8px 0', paddingLeft: 18 }}>
            <li>Covenant DSCR di <strong>Aqua World</strong> in avvicinamento alla soglia contrattuale <span className="ai-citation">1.20×<sup>⇱</sup></span></li>
            <li>Marginalità <strong>Club Lumière</strong> −3.6 p.p. vs budget stagionale <span className="ai-citation">Budget 2026<sup>⇱</sup></span></li>
          </ul>
          Vuoi che generi un brief prioritizzato?
        </>
      )
    }
  ]);
  const [input, setInput] = React.useState('');

  const quickPrompts = [
    { icon: 'sparkle', text: "Riepilogo settimanale del gruppo" },
    { icon: 'clock', text: "Quali scadenze nei prossimi 30 giorni?" },
    { icon: 'chat', text: "Confronta EBITDA 2025 vs 2026 per società" },
    { icon: 'file', text: "Genera report trimestrale per il CdA" }
  ];

  const send = () => {
    if (!input.trim()) return;
    setMessages(m => [...m, { role: 'user', content: input }, {
      role: 'ai',
      content: <>Elaboro la risposta sul perimetro <strong>{scope}</strong>… <span className="text-muted">(demo)</span></>
    }]);
    setInput('');
  };

  return (
    <aside className="chat-panel">
      <div className="chat-head">
        <div className="ai-avatar" style={{ width: 22, height: 22, borderRadius: 5, background: 'var(--accent)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'var(--f-mono)', fontSize: 11, fontWeight: 600 }}>R</div>
        <div style={{ flex: 1 }}>
          <div className="chat-head-title">Chiedi a Regula</div>
          <div className="chat-head-scope">Scope · {scope}{company ? ` · ${company}` : ''}</div>
        </div>
        <button className="btn" style={{ padding: '3px 6px' }} onClick={onExpand} title="Apri a tutta pagina">
          <Icon name="expand" size={12} />
        </button>
      </div>

      <div className="chat-body">
        {messages.map((m, i) => (
          m.role === 'ai' ? (
            <div key={i} className="msg ai">
              <div className="ai-avatar">R</div>
              <div className="ai-content">{m.content}</div>
            </div>
          ) : (
            <div key={i} className="msg user">{m.content}</div>
          )
        ))}

        <div style={{ marginTop: 6 }}>
          <div className="chat-scope-row">Suggeriti</div>
          <div className="quick-prompts">
            {quickPrompts.map((q, i) => (
              <button key={i} className="quick-prompt" onClick={() => setInput(q.text)}>
                <span className="qp-icon"><Icon name={q.icon} size={12} /></span>
                <span>{q.text}</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="chat-input-wrap">
        <div className="chat-input">
          <textarea
            placeholder={`Chiedi a Regula su ${scope}…`}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            rows={1}
          />
          <button className="chat-send" onClick={send}><Icon name="send" size={12} /></button>
        </div>
        <div style={{ marginTop: 6, display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
          <span>↵ invia · ⇧↵ a capo</span>
          <span>GPT-4.1 · privato</span>
        </div>
      </div>
    </aside>
  );
};

// ───────────────────────────── Full chat page
const ChatFullPage = () => {
  const [scope, setScope] = React.useState('group');
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [selectedCompanies, setSelectedCompanies] = React.useState(new Set());

  const D = window.REGULA_DATA;

  const scopeLabel = scope === 'group' ? 'Tutto il gruppo'
    : scope === 'single' ? 'Singola società'
    : 'Insieme di società';

  const prompts = [
    { tag: "Report", text: "Genera il report trimestrale Q1 2026 per Aqua World" },
    { tag: "Forecast", text: "Previsione cash flow del gruppo a 6 mesi" },
    { tag: "Confronto", text: "Confronta la marginalità 2024 vs 2025 di tutte le società" },
    { tag: "Rischio", text: "Quale società ha l'esposizione debitoria più critica?" }
  ];

  const exampleResponse = (q) => ({
    role: 'ai',
    content: (
      <>
        <p style={{ margin: '0 0 10px' }}>Analizzando i bilanci consolidati <span className="ai-citation">Bilancio 2025<sup>1</sup></span> e la policy di tesoreria <span className="ai-citation">Policy v3.2<sup>2</sup></span>, l'esposizione debitoria più critica è di <strong>Aqua World</strong>: PFN/EBITDA = 3.8×, con covenant DSCR a 1.24× (soglia 1.20×).</p>
        <div className="msg-table">
          <table>
            <thead>
              <tr>
                <th>Società</th>
                <th>PFN</th>
                <th>PFN/EBITDA</th>
                <th>DSCR</th>
                <th>Stato</th>
              </tr>
            </thead>
            <tbody>
              <tr><td>Aqua World</td><td className="n">24.8 M€</td><td className="n">3.80×</td><td className="n">1.24×</td><td><span className="chip red">A rischio</span></td></tr>
              <tr><td>MetalTech Industries</td><td className="n">38.2 M€</td><td className="n">1.82×</td><td className="n">2.10×</td><td><span className="chip green">OK</span></td></tr>
              <tr><td>Club Lumière</td><td className="n">4.1 M€</td><td className="n">7.70×</td><td className="n">0.92×</td><td><span className="chip red">Sforato</span></td></tr>
              <tr><td>Fond. Arte Contemporanea</td><td className="n">0.3 M€</td><td className="n">0.14×</td><td className="n">—</td><td><span className="chip green">OK</span></td></tr>
            </tbody>
          </table>
        </div>
        <p style={{ margin: '10px 0 0' }}>Nota: Club Lumière ha DSCR &lt; 1.0 ma trattasi di situazione stagionale; trend atteso in recupero entro Q3.</p>
        <div className="msg-actions">
          <button className="btn"><Icon name="download" size={12} /> PDF</button>
          <button className="btn"><Icon name="download" size={12} /> Excel</button>
          <button className="btn"><Icon name="file" size={12} /> Salva come report</button>
        </div>
      </>
    )
  });

  const send = (text) => {
    const q = text || input;
    if (!q.trim()) return;
    setMessages(m => [...m, { role: 'user', content: q }, exampleResponse(q)]);
    setInput('');
  };

  return (
    <div className="chat-full">
      <div className="topbar">
        <div className="breadcrumb">
          <span>Regula</span>
          <span className="sep">/</span>
          <span className="current">Chat</span>
        </div>
        <div className="topbar-spacer" />
        <button className="btn"><Icon name="clock" size={12} /> Cronologia</button>
        <button className="btn-primary btn"><Icon name="plus" size={12} /> Nuova chat</button>
      </div>

      <div className="scope-bar">
        <span style={{ fontFamily: 'var(--f-mono)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)' }}>Perimetro</span>
        <div className="scope-seg">
          <button className={scope === 'group' ? 'active' : ''} onClick={() => setScope('group')}>Tutto il gruppo</button>
          <button className={scope === 'single' ? 'active' : ''} onClick={() => setScope('single')}>Singola società</button>
          <button className={scope === 'multi' ? 'active' : ''} onClick={() => setScope('multi')}>Insieme di società</button>
        </div>
        {scope === 'single' && (
          <select className="pill-select" style={{ padding: '4px 10px' }}>
            {D.companies.map(c => <option key={c.id}>{c.name}</option>)}
          </select>
        )}
        {scope === 'multi' && (
          <div style={{ display: 'flex', gap: 4 }}>
            {D.companies.map(c => (
              <button key={c.id} className="chip accent" style={{ cursor: 'pointer', padding: '3px 8px' }}>
                {c.short}
              </button>
            ))}
          </div>
        )}
        <div style={{ flex: 1 }} />
        <span style={{ fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--muted)' }}>124 documenti nel perimetro</span>
      </div>

      <div className="chat-full-body">
        <div className="chat-full-inner">
          {messages.length === 0 ? (
            <div className="chat-empty">
              <div className="mark">R</div>
              <h2>Chiedi a Regula</h2>
              <p>Analisi del patrimonio di gruppo, previsioni, confronti tra società e generazione di report — con citazioni alla knowledge base.</p>
              <div className="empty-prompts">
                {prompts.map((p, i) => (
                  <button key={i} className="empty-prompt" onClick={() => send(p.text)}>
                    <span className="ep-tag">{p.tag}</span>
                    <span className="ep-text">{p.text}</span>
                  </button>
                ))}
              </div>
            </div>
          ) : (
            messages.map((m, i) => (
              m.role === 'ai' ? (
                <div key={i} className="msg ai">
                  <div className="ai-avatar">R</div>
                  <div className="ai-content">{m.content}</div>
                </div>
              ) : (
                <div key={i} className="msg user" style={{ fontSize: 14 }}>{m.content}</div>
              )
            ))
          )}
        </div>
      </div>

      <div style={{ borderTop: '1px solid var(--border)', padding: '16px 48px', background: 'var(--bg)' }}>
        <div style={{ maxWidth: 780, margin: '0 auto' }}>
          <div className="chat-input" style={{ padding: '10px 12px' }}>
            <textarea
              placeholder={`Chiedi a Regula — perimetro: ${scopeLabel.toLowerCase()}`}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              rows={1}
              style={{ fontSize: 14 }}
            />
            <button className="chat-send" onClick={() => send()}><Icon name="send" size={12} /></button>
          </div>
          <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            <span>Le risposte includono citazioni verificabili alla knowledge base</span>
            <span>GPT-4.1 · dati privati</span>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ChatSidebar, ChatFullPage });
