// intelligence.jsx — MeetCard (species intro) + Ask Tendlet demo chat

// ─── MeetCard ────────────────────────────────────────────────────────────
// Beautiful editorial intro to a species. Used in onboarding (between
// species pick + naming) and on Detail page.
function MeetCard({ kind, species, iconKey, em, tint, custom, onContinue, embedded = false }) {
  const speciesLabel = String(species || '');
  const iconSource = { species: speciesLabel, iconKey };
  const care = window.careFor(speciesLabel, kind);
  if (!care) return null;
  const diffWord = ['easy', 'easy-ish', 'moderate', 'demanding', 'expert'][care.difficulty - 1];
  const diffColor = care.difficulty <= 2 ? 'var(--forest)' : care.difficulty <= 3 ? 'var(--honey)' : 'var(--terra)';

	  return (
	    <div className={'meet' + (embedded ? ' embedded' : '')}>
	      <div className="meet-hero" data-tint={tint}>
	        <div className="meet-grain"></div>
	        <window.SpeciesIcon species={iconSource} kind={kind} className="meet-icon-img" fallbackClassName="meet-em" fallback={em} />
        <div className="meet-h">
          <div className="meet-kicker">Meet your</div>
          <h2 className="meet-name">{speciesLabel.slice(0, -1)}<i>{speciesLabel.slice(-1)}</i>.</h2>
          {care.level && <div className="meet-level"><i>"{care.level}."</i></div>}
        </div>
      </div>

      <div className="meet-stats">
        <div className="meet-stat">
          <label>Difficulty</label>
          <div className="meet-dots" style={{ color: diffColor }}>
            {[1, 2, 3, 4, 5].map((i) => (
              <span key={i} className={i <= care.difficulty ? 'on' : ''}></span>
            ))}
          </div>
          <div className="meet-diff" style={{ color: diffColor }}>{diffWord}</div>
        </div>
        <div className="meet-stat">
          <label>Lifespan</label>
          <div className="meet-life h-serif">{care.lifespan}</div>
        </div>
      </div>

      <div className="meet-section">
        <div className="meet-section-h">
          <span>What they need</span>
          <em>essentials</em>
        </div>
        <ul className="meet-list good">
          {care.needs.map((n, i) => (
            <li key={i}>
              <span className="bullet">○</span>
              <span>{n}</span>
            </li>
          ))}
        </ul>
      </div>

      <div className="meet-section">
        <div className="meet-section-h">
          <span>Common mistakes</span>
          <em>avoid</em>
        </div>
        <ul className="meet-list bad">
          {care.mistakes.map((n, i) => (
            <li key={i}>
              <span className="bullet">×</span>
              <span>{n}</span>
            </li>
          ))}
        </ul>
      </div>

      {care.headsup && (
        <div className="meet-headsup">
          <div className="hu-q">"</div>
          <div className="hu-text">{care.headsup}</div>
        </div>
      )}

      {!embedded && onContinue && (
        <button className="cta" onClick={onContinue}>Continue → give them a name</button>
      )}
    </div>
  );
}

// ─── Ask Tendlet — demo chat sheet ───────────────────────────────────────
function demoCareReply(text, contextFolk, folks) {
  const q = (text || '').toLowerCase();
  const folk = contextFolk || (folks || [])[0] || null;
  const species = folk?.species || 'your folk';
  const name = folk?.name || 'they';
  const care = folk ? window.careFor(folk.species, folk.kind) : null;
  let reply;

  if (q.includes('vet') || q.includes('sick') || q.includes('symptom') || q.includes('off') || q.includes('worry')) {
    reply = `${name} deserves a cautious read. Look for appetite, energy, breathing, stool, and whether the change is getting worse; if any symptom is sudden, painful, or persistent, call a vet.`;
  } else if (q.includes('stress') || q.includes('behaviour') || q.includes('behavior')) {
    reply = `For a ${species}, stress usually shows as hiding, appetite changes, unusual stillness, over-grooming, or a sudden change in routine. Compare today to ${name}'s normal baseline, then reduce noise and handling while you observe.`;
  } else if (q.includes('water') || q.includes('dry') || q.includes('leaves')) {
    reply = folk?.kind === 'plant'
      ? `${name} wants you to check the soil before acting. Water deeply only when the top layer matches their care rhythm, then let the pot drain so roots do not sit wet.`
      : `Fresh water is still care, even when the question is not about plants. Refill, wash the bowl, and watch whether ${name} is drinking much more or less than usual.`;
  } else if (q.includes('food') || q.includes('eat') || q.includes('feed')) {
    reply = `Keep the feeding plan boring in the best way: steady amounts, clean water, and slow changes. For ${species}, sudden appetite loss is worth a vet call, especially if it pairs with lethargy or pain.`;
  } else if (q.includes('mistake') || q.includes('new')) {
    reply = care?.mistakes?.length
      ? `The common trap with ${species}: ${care.mistakes[0].toLowerCase()}. Start with the basics, then adjust one variable at a time so you can tell what helped.`
      : `The common new-caretaker mistake is changing too much at once. Keep routine, food, water, and light steady while you learn their normal signals.`;
  } else {
    const need = care?.needs?.[0] || 'a steady routine, clean water, and careful observation';
    reply = `${species} care starts with ${need.toLowerCase()}. Tendlet's rule of thumb: notice the small changes early, keep notes, and ask a professional when health feels uncertain.`;
  }

  return new Promise((resolve) => setTimeout(() => resolve(reply), 520));
}

function AskTendlet({ open, onClose, folks, contextFolk }) {
  const greeting = contextFolk
    ? `Ask me anything about ${contextFolk.name} — care, behaviour, when to worry.`
    : `Hi. I know your folk. Ask me anything — small worries, daily routines, the strange thing they just did.`;

  const [messages, setMessages] = React.useState([{ role: 'assistant', text: greeting }]);
  const [input, setInput] = React.useState('');
  const [thinking, setThinking] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, thinking]);

  // Reset on each open with a fresh greeting that reflects current context
  React.useEffect(() => {
    if (open) {
      setMessages([{ role: 'assistant', text: greeting }]);
      // If app set a prefill prompt, auto-send it once the chat is open
      if (window.__askPrefill) {
        const p = window.__askPrefill;
        window.__askPrefill = null;
        setTimeout(() => send(p), 60);
      } else {
        setInput('');
      }
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, contextFolk?.id]);

  const folksList = (folks || []).map((f) => `${f.name} (${f.species}, ${f.kind})`).join('; ');
  const sysContext = `You are Tendlet, a warm but precise plant-and-animal-care companion inside a phone app.
Voice: kind, gently editorial, like a friend who reads. Use plain language. Italics sparingly. No emoji unless mirroring the user's.
Brevity: 2–4 sentences, max ~80 words. Be willing to say "I don't know — check with a vet."
Safety: for any sign of illness, advise a vet visit. Never give medication doses.
The user keeps these folk: ${folksList || 'no folk yet'}.
${contextFolk ? `They are asking specifically about ${contextFolk.name}, a ${contextFolk.species}${contextFolk.breed ? ' (' + contextFolk.breed + ')' : ''}, kind: ${contextFolk.kind}.` : ''}`;

  const send = async (q) => {
    const text = (q ?? input).trim();
    if (!text || thinking) return;
    const newMsgs = [...messages, { role: 'user', text }];
    setMessages(newMsgs);
    setInput('');
    setThinking(true);
    try {
      // Build a single prompt to be safe with claude.complete's string mode
      const history = newMsgs.slice(0, -1).map((m) =>
        (m.role === 'user' ? 'User: ' : 'Tendlet: ') + m.text).join('\n\n');
      const prompt = `${sysContext}\n\n${history ? history + '\n\n' : ''}User: ${text}\n\nTendlet:`;
      const reply = window.claude && typeof window.claude.complete === 'function'
        ? await window.claude.complete(prompt)
        : await demoCareReply(text, contextFolk, folks);
      setMessages((m) => [...m, { role: 'assistant', text: reply.trim() }]);
    } catch (e) {
      const fallback = await demoCareReply(text, contextFolk, folks);
      setMessages((m) => [...m, { role: 'assistant', text: fallback.trim() }]);
    }
    setThinking(false);
  };

  const suggestions = contextFolk
    ? [
        `What worries you most about a ${contextFolk.species}?`,
        `How do I tell if ${contextFolk.name} is stressed?`,
        `What's a common mistake new owners make?`,
      ]
    : [
        `Why might a plant drop leaves suddenly?`,
        `My pet seems off — what should I look for?`,
        `What signs mean it's time to call a vet?`,
      ];

  if (!open) return null;

  return (
    <div className="ask-overlay" onClick={onClose}>
      <div className="ask-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="ask-handle"></div>
        <div className="ask-hd">
          <div>
            <div className="ask-kicker">Ask</div>
            <div className="ask-title">Ask Tendlet</div>
          </div>
          {contextFolk && (
            <div className="ask-ctx">
              <window.FolkAvatar folk={contextFolk} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{contextFolk.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{contextFolk.species}</div>
              </div>
            </div>
          )}
          <button className="ask-x" onClick={onClose} aria-label="Close">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="1.8" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
          </button>
        </div>

        <div className="ask-msgs" ref={scrollRef}>
          {messages.map((m, i) => (
            <div key={i} className={'ask-msg ' + m.role}>
              {m.role === 'assistant' && i === 0 && (
                <div className="ask-msg-kicker">Tendlet says</div>
              )}
              <div className="ask-bubble">{m.text}</div>
            </div>
          ))}
          {thinking && (
            <div className="ask-msg assistant">
              <div className="ask-bubble thinking">
                <span></span><span></span><span></span>
              </div>
            </div>
          )}
        </div>

        {messages.length <= 1 && !thinking && (
          <div className="ask-suggest">
            <div className="ask-suggest-h">Try asking</div>
            {suggestions.map((s, i) => (
              <button key={i} onClick={() => send(s)}>
                <span>{s}</span>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M13 6l6 6-6 6"/>
                </svg>
              </button>
            ))}
          </div>
        )}

        <div className="ask-input">
          <input value={input} onChange={(e) => setInput(e.target.value)}
                 onKeyDown={(e) => e.key === 'Enter' && send()}
                 placeholder="Ask anything…" disabled={thinking} />
          <button onClick={() => send()} disabled={!input.trim() || thinking} aria-label="Send">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14M13 6l6 6-6 6"/>
            </svg>
          </button>
        </div>
        <div className="ask-disclaimer">Tendlet is an assistant — not a vet. For symptoms, see a professional.</div>
      </div>
    </div>
  );
}

// ─── Inline "Ask" button — drops anywhere ──────────────────────────────
function AskButton({ label = 'Ask Tendlet', folk, onOpen }) {
  return (
    <button className="ask-cta" onClick={() => onOpen(folk)}>
      <div className="ask-cta-ic">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
             strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 3l1.8 4.5L18 9l-4.2 1.5L12 15l-1.8-4.5L6 9l4.2-1.5z"/>
          <circle cx="18" cy="18" r="1.5" fill="currentColor"/>
          <circle cx="5" cy="17" r="1" fill="currentColor"/>
        </svg>
      </div>
      <div className="ask-cta-t">
        <b>{label}</b>
        <span>{folk ? `Anything about ${folk.name}` : 'Anything about your folk'}</span>
      </div>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
           strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--ink-3)' }}>
        <path d="M9 6l6 6-6 6"/>
      </svg>
    </button>
  );
}

Object.assign(window, { MeetCard, AskTendlet, AskButton });
