// admin/pages/rinpo.jsx — RINPO workspace (query engine + action center)

function RinpoPage({ go }) {
  const [q, setQ] = React.useState('');
  const [answer, setAnswer] = React.useState(null);
  const data = OwnerMetrics.rinpoInsights();
  const intel = window.OwnerIntelligence || null;
  const briefing = intel && intel.dailyBriefing ? intel.dailyBriefing() : null;
  const pulse = intel && intel.businessPulse ? intel.businessPulse() : null;
  const actions = intel && intel.actionCenter ? intel.actionCenter() : [];

  const ask = (e) => {
    e && e.preventDefault();
    const text = (q || '').trim();
    if (/refund|sql|delete all|drop /i.test(text)) {
      setAnswer({
        title: 'Not allowed',
        body: 'RINPO cannot execute SQL, refunds, or destructive bulk actions. Use authorized owner screens with confirmation.',
        href: null,
        citations: [],
      });
      return;
    }
    if (intel && intel.ask) {
      const res = intel.ask(text);
      if (res) {
        setAnswer({
          title: res.title,
          body: res.summary + (res.insufficientData ? '\n\n(I don\'t have enough data for a confident answer on parts of this.)' : ''),
          href: res.citations && res.citations[0] ? res.citations[0].href : null,
          citations: res.citations || [],
          evidence: res.evidence || [],
        });
        return;
      }
    }
    setAnswer({
      title: 'Try a question',
      body: 'Examples: "How is business doing?", "Which products are low in stock?", "What sold most this month?", "What needs my attention?"',
      href: null,
      citations: [],
    });
  };

  return (
    <div>
      <div className="mode-banner">RINPO · Intelligence Fabric query engine. Answers use validated metrics and source traces — never invented numbers. High-risk commands require Runtime approval.</div>
      <h2 className="serif" style={{ fontSize: '1.5rem', marginBottom: 8 }}>RINPO</h2>
      <p className="muted" style={{ marginBottom: 16 }}>Ask · Business pulse · Action center · Recommendations</p>

      {(pulse || briefing) && (
        <div className="card card-pad" style={{ marginBottom: 16 }}>
          <div className="section-title">{(pulse && pulse.title) || (briefing && briefing.title) || 'Business pulse'}</div>
          <ul className="action-list">
            {((pulse && pulse.lines) || (briefing && briefing.lines) || []).map((line, i) => <li key={i}>{line}</li>)}
          </ul>
          {pulse && pulse.pulse && pulse.pulse.needsAttention && pulse.pulse.needsAttention.length > 0 && (
            <p style={{ marginTop: 10, fontSize: '.85rem' }}><b>Needs attention:</b> {pulse.pulse.needsAttention.join(' · ')}</p>
          )}
        </div>
      )}

      <form className="card card-pad" onSubmit={ask} style={{ marginBottom: 16 }}>
        <label className="field"><span>Ask</span>
          <input className="inp" value={q} onChange={(e) => setQ(e.target.value)} placeholder="How is business doing?" />
        </label>
        <button className="btn btn-primary" type="submit" style={{ marginTop: 10 }}>Ask</button>
        {answer && (
          <div className="rinpo-answer">
            <b>{answer.title}</b>
            <p style={{ whiteSpace: 'pre-wrap' }}>{answer.body}</p>
            {answer.evidence && answer.evidence.length > 0 && (
              <details style={{ marginTop: 8, fontSize: '.8rem' }}>
                <summary>Source evidence</summary>
                <ul>{answer.evidence.map((ev, i) => <li key={i}>{ev}</li>)}</ul>
              </details>
            )}
            {answer.citations && answer.citations.map((c, i) => (
              c.href ? <a key={i} className="btn btn-soft btn-sm" href={c.href} style={{ marginRight: 6 }}>{c.label}</a> : null
            ))}
            {answer.href && !answer.citations.length && <a className="btn btn-soft btn-sm" href={answer.href}>Open</a>}
          </div>
        )}
      </form>

      {actions.length > 0 && (
        <div className="card card-pad" style={{ marginBottom: 16 }}>
          <div className="section-title">Action center</div>
          <div className="card-list">
            {actions.slice(0, 8).map((card) => (
              <div className="card-row" key={card.id} style={{ flexDirection: 'column', alignItems: 'flex-start', gap: 4 }}>
                <span className="badge b-new">{card.title}</span>
                <div>{card.body}</div>
                {card.evidence && card.evidence.length > 0 && (
                  <div className="muted" style={{ fontSize: '.75rem' }}>{card.evidence.join(' · ')}</div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="card card-pad">
        <div className="section-title">Live insights</div>
        <ul className="action-list">
          {data.tips.map((t, i) => (
            <li key={i}><a href={t.href}>{t.text}</a></li>
          ))}
        </ul>
      </div>
    </div>
  );
}
window.RinpoPage = RinpoPage;
