// Persistent AI agent panel — chat, voice, image attachments.
// Drives the main canvas via the `onAgentAction` callback.

const { useState, useRef, useEffect } = React;

// Agent scripted responses keyed off lightweight intent detection.
// Returns { reply, action }.
function think(input) {
  const t = input.toLowerCase();
  if (t.includes('fridge') || t.includes('scan') || t.includes('photo')) {
    return {
      reply: "Snap a photo and I'll see what you've got. Anything past its prime gets a gentle ❋ nudge.",
      action: { screen: 'fridge' },
      followUp: { chips: [{ label: 'Use the demo fridge', accent: true, send: 'demo fridge' }] }
    };
  }
  if (t.includes('demo fridge') || t.includes('use the demo')) {
    return {
      reply: "Scanning… I see tomatoes (4), eggs (2 left), almost-empty milk, fresh spinach, half a butter. Want a 30-minute Italian using the tomatoes?",
      action: { screen: 'fridge', scanned: true },
      followUp: { chips: [
        { label: 'Yes — show me one', accent: true, send: 'show me a 30 min italian with tomatoes' },
        { label: 'Just restock the basics', send: 'restock' },
      ]}
    };
  }
  if (t.includes('tomato') || t.includes('italian') || t.includes('pasta') || t.includes('30 min')) {
    return {
      reply: "Pomodoro it is — bronze-cut spaghetti, vine toms, garlic, basil. 22 min, serves two. I've added what's missing to your basket; you already have olive oil & pasta.",
      action: { screen: 'recipe', recipeId: 'r-pomod', autoAdd: true },
    };
  }
  if (t.includes('chicken') || t.includes('spinach')) {
    return {
      reply: "Two strong calls: lemon-thyme chicken with wilted spinach, or a quick saag. Both under 30 min. Lean tonight or batch for the week?",
      action: { screen: 'recipes' },
      followUp: { chips: [
        { label: 'Tonight, lean', accent: true, send: 'pomodoro' },
        { label: 'Batch for the week', send: 'weekly basket' },
      ]}
    };
  }
  if (t.includes('basket') || t.includes('cart') || t.includes('weekly')) {
    return {
      reply: "Pulled a weekly basket for two — ~$58. I held back on cheese (you've got plenty) and bumped milk (you're nearly out).",
      action: { screen: 'basket', preset: 'weekly' },
    };
  }
  if (t.includes('checkout') || t.includes('pay')) {
    return {
      reply: "Locked. Pick a slot — Thursday 6–7pm is free delivery on orders over $40 today.",
      action: { screen: 'checkout' },
    };
  }
  if (t.includes('track') || t.includes('order') || t.includes('eta')) {
    return {
      reply: "Sam is 7 minutes out. They're carrying a cold bag — the burrata's behaving.",
      action: { screen: 'tracking' },
    };
  }
  if (t.includes('pantry') || t.includes('what do i have')) {
    return {
      reply: "You're low on eggs, milk, and red onion. Coffee is creeping down too. Want me to drop a top-up in the basket?",
      action: { screen: 'pantry' },
      followUp: { chips: [{ label: 'Yes, top me up', accent: true, send: 'top up pantry' }]},
    };
  }
  if (t.includes('top up') || t.includes('restock')) {
    return {
      reply: "Done. $11.40 added — eggs, milk, red onion, a fresh tin of coffee. Want me to schedule this weekly?",
      action: { screen: 'basket', preset: 'restock' },
    };
  }
  if (t.includes('surprise') || t.includes('italian under')) {
    return {
      reply: "Caprese with the good buffalo mozzarella, then arrabbiata. $23.40, ready in 35.",
      action: { screen: 'recipes' },
    };
  }
  if (t.includes('catalog') || t.includes('browse') || t.includes('aisle') || t.includes('shop ') || t.includes('buy this week') || t.includes('the shop')) {
    return {
      reply: "Opening the aisles — sorted by department. Tap any product to see where it's from and why I stock it.",
      action: { screen: 'catalog' },
    };
  }
  if (t.includes('tell me more about') || t.includes('tell me about the')) {
    return {
      reply: "Good eye. It's one of the few we hand-check on arrival — small producer, fair terms, and it earns its place. Want me to drop it in the basket?",
    };
  }
  if (t.includes('qatayef') || t.includes('katayef') || t.includes('ramadan') || t.includes('dessert')) {
    return {
      reply: "Pulling up Classic Qatayef dough — 28 years in the making, by منى الحسون. I've got the method, the macros, and the video. The batter's blender-easy.",
      action: { screen: 'recipe', recipeId: 'r-qatayef' },
    };
  }
  if (t.includes('business') || t.includes('sell with') || t.includes('sell in') || t.includes('sell my') || t.includes('launch') || t.includes('indie chef') || t.includes('local brand') || t.includes('partner') || t.includes('wholesale') || t.includes('book a call')) {
    return {
      reply: "Love it. blyzr partners with brands three ways — Sell in the US, Launch your product, and Sell with us. Tell me what you make and roughly where you're based, and I'll route you to the right team.",
      action: { screen: 'business' },
    };
  }
  if (t.includes('café') || t.includes('cafe') || t.includes('location') || t.includes('opening') || t.includes('a spot') || t.includes('coffee shop')) {
    return {
      reply: "The blyzr café — the app made a room: a coffee, the week's recipe cooking, and a smell you'll remember. We're scouting our first home in East London. Got a corner in mind, or want me to flag you when it opens?",
      action: { screen: 'cafe' },
    };
  }
  // default
  return {
    reply: "I can do recipes, scan a fridge photo, build a weekly basket, or just chat about dinner. What sounds good?",
    followUp: { chips: [
      { label: 'Scan my fridge', send: 'scan my fridge' },
      { label: 'Weekly basket', send: 'weekly basket' },
      { label: 'Surprise me', accent: true, send: 'surprise me' },
    ]},
  };
}

// Message: { id, role: 'agent'|'user', text, chips?, card? }
const Composer = ({ onSend, onMic, onAttach, listening }) => {
  const [v, setV] = useState('');
  const ref = useRef(null);
  const submit = () => {
    const text = v.trim();
    if (!text) return;
    onSend(text);
    setV('');
    if (ref.current) ref.current.style.height = 'auto';
  };
  return (
    <div className="composer">
      <div className="composer-row">
        <button className="icon-btn" onClick={onAttach} title="Attach fridge photo"><Icon.attach/></button>
        <textarea
          ref={ref}
          rows={1}
          value={v}
          onChange={(e) => {
            setV(e.target.value);
            e.target.style.height = 'auto';
            e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px';
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); }
          }}
          placeholder="Ask Blyzr anything…"
        />
        <div className="composer-actions">
          <button className={`icon-btn ${listening ? 'active' : ''}`} onClick={onMic} title="Hold to talk" style={listening ? { color: 'var(--accent-ink)', background: 'var(--accent-soft)' } : {}}>
            <Icon.mic/>
          </button>
          <button className="send" onClick={submit} disabled={!v.trim()} aria-label="Send"><Icon.send/></button>
        </div>
      </div>
      <div className="composer-hint">
        <span>Press <kbd>↵</kbd> to send · <kbd>⌘ K</kbd> for ideas</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }}/>
          Encrypted
        </span>
      </div>
    </div>
  );
};

const AgentPanel = ({ messages, typing, onSend, listening, onMic, onAttach, open, onClose }) => {
  const bodyRef = useRef(null);
  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, typing]);

  return (
    <aside className={`agent ${open ? 'open' : ''}`}>
      <div className="agent-head">
        <div className="label">
          <OrbMini/>
          <span>Blyzr · live</span>
        </div>
        <div className="agent-head-actions">
          <button className="icon-btn" title="Read aloud"><Icon.sound/></button>
          <button className="icon-btn" title="Options"><Icon.more/></button>
          <button className="icon-btn" title="Close" onClick={onClose}><Icon.x/></button>
        </div>
      </div>

      <div className="agent-body" ref={bodyRef}>
        {messages.map((m) => (
          <Message key={m.id} m={m} onSend={onSend}/>
        ))}
        {typing && (
          <div className="msg msg-agent">
            <div className="typing"><span/><span/><span/></div>
          </div>
        )}
      </div>

      <Composer onSend={onSend} onMic={onMic} onAttach={onAttach} listening={listening}/>
    </aside>
  );
};

const Message = ({ m, onSend }) => {
  if (m.role === 'user') {
    return (
      <div className="msg msg-user">
        <div className="msg-bubble">{m.text}</div>
      </div>
    );
  }
  return (
    <div className="msg msg-agent">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, maxWidth: '92%' }}>
        <div className="msg-bubble">{m.text}</div>
        {m.chips && (
          <div className="chips">
            {m.chips.map((c, i) => (
              <button key={i} className={`chip ${c.accent ? 'accent' : ''}`} onClick={() => onSend(c.send || c.label)}>
                {c.label} <Icon.arrow style={{ width: 12, height: 12 }}/>
              </button>
            ))}
          </div>
        )}
        {m.card}
      </div>
    </div>
  );
};

window.AgentPanel = AgentPanel;
window.think = think;
