/* Sentosa Marketplace - Buyer Portal: AI itinerary planning
   S/No. 120 AI-powered itinerary planning and product recommendations, on machine learning
             and SDC-approved knowledge training
   S/No. 121 Personalised journeys, predictive forecasting of trends and buyer behaviour to support
             commission target achievement, and the option to convert AI recommendations directly to purchase
   Reply No. 4 Q7: mandatory Phase 1. All AI processing and data resides in Singapore.
                   No standalone chatbot is claimed - this is the itinerary/recommendation surface only. */

function AiItineraryScreen({ onAddAll, onBack, onOpen }) {
  const [brief, setBrief] = React.useState("");
  const [stage, setStage] = React.useState("idle"); // idle | thinking | result
  const plan = window.AI_ITINERARY;

  const run = (text) => {
    setBrief(text); setStage("thinking");
    setTimeout(() => setStage("result"), 900);
  };

  const resolved = plan.days.map(d => ({
    ...d,
    items: d.picks.map(p => ({ ...window.PRODUCTS.find(x => x.id === p.id), qty: p.qty })).filter(x => x.id),
  }));
  const all = resolved.flatMap(d => d.items);
  const total = all.reduce((s, i) => s + i.trade * i.qty, 0);
  const partners = [...new Set(all.map(i => i.partner))];

  return (
    <div>
      <div style={{ background: "var(--black)", color: "#fff" }}>
        <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "40px 24px 44px" }}>
          <div className="overline" style={{ color: "var(--orange-300)" }}>AI itinerary planning · Phase 1</div>
          <h1 style={{ color: "#fff", fontSize: "2.2rem", margin: "8px 0 10px", maxWidth: 660 }}>Describe the trip. We'll build the itinerary.</h1>
          <p style={{ fontSize: 16.5, color: "#C9C9C9", maxWidth: 620, lineHeight: 1.55, marginBottom: 22 }}>
            Grounded on SDC-approved island content and your contracted rates. Every suggestion is a real, bookable
            product - convert the whole itinerary to an order in one click.
          </p>
          <div style={{ maxWidth: 760 }}>
            <div style={{ display: "flex", gap: 10 }}>
              <div style={{ position: "relative", flex: 1 }}>
                <span style={{ position: "absolute", left: 14, top: 16, display: "flex" }}><Icon name="sparkles" size={18} color="var(--orange-300)" /></span>
                <textarea value={brief} onChange={e => setBrief(e.target.value)}
                  placeholder="e.g. 3-day incentive group of 40 pax, mix of attractions and beachfront dining, under S$180 per pax"
                  aria-label="Describe the itinerary you need" rows={2}
                  style={{ width: "100%", boxSizing: "border-box", padding: "14px 14px 14px 44px", borderRadius: "var(--radius-md)",
                    border: "1.5px solid #3a3a3a", background: "#262626", color: "#fff", fontSize: 15,
                    fontFamily: "var(--font-sans)", outline: "none", resize: "vertical", lineHeight: 1.5 }} />
              </div>
              <Btn variant="primary" onClick={() => brief.trim() && run(brief)} icon="wand-sparkles">Generate</Btn>
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 14, alignItems: "center" }}>
              <span style={{ fontSize: 12.5, color: "#9A9A9A" }}>Try:</span>
              {window.AI_PROMPTS.map(s => (
                <button key={s} onClick={() => run(s)}
                  style={{ background: "#262626", border: "1px solid #3a3a3a", color: "#C9C9C9", borderRadius: "var(--radius-pill)",
                    padding: "6px 13px", fontSize: 12.5, cursor: "pointer", fontFamily: "var(--font-sans)" }}>{s}</button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "26px 24px" }}>
        {stage === "idle" && (
          <Card style={{ textAlign: "center", padding: 56 }}>
            <Icon name="sparkles" size={30} color="var(--fg3)" />
            <div style={{ fontWeight: 600, marginTop: 12, fontSize: 16 }}>No itinerary yet</div>
            <p className="caption" style={{ marginTop: 6, marginBottom: 0 }}>Enter a brief above, or pick one of the examples.</p>
          </Card>
        )}

        {stage === "thinking" && (
          <Card style={{ display: "flex", alignItems: "center", gap: 14, padding: 26 }}>
            <Icon name="loader" size={20} color="var(--orange-900)" />
            <div>
              <div style={{ fontWeight: 600 }}>Building your itinerary…</div>
              <div className="caption">Matching the brief against your contracted FY26 rates and live island availability.</div>
            </div>
          </Card>
        )}

        {stage === "result" && (
          <>
            {/* Rationale */}
            <Card style={{ marginBottom: 20 }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <AiChip />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 17, fontWeight: 700, marginBottom: 6 }}>{plan.title}</div>
                  <p style={{ fontSize: 14.5, color: "var(--fg2)", lineHeight: 1.6, margin: "0 0 14px" }}>{plan.rationale}</p>
                  <div style={{ display: "flex", gap: 22, flexWrap: "wrap", fontSize: 13.5 }}>
                    <span><span style={{ color: "var(--fg2)" }}>Per pax</span> <strong>S${plan.perPax.toFixed(2)}</strong></span>
                    <span><span style={{ color: "var(--fg2)" }}>Island partners</span> <strong>{partners.length}</strong></span>
                    <span><span style={{ color: "var(--fg2)" }}>Order value</span> <strong>S${total.toLocaleString(undefined, { minimumFractionDigits: 2 })}</strong></span>
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--fg2)", marginTop: 12, display: "flex", alignItems: "center", gap: 6 }}>
                    <Icon name="shield-check" size={14} color="var(--success)" />
                    Grounded on SDC-approved catalogue content. All AI processing and data resides in Singapore.
                  </div>
                </div>
              </div>
            </Card>

            {/* Predictive insight - S/No. 121 */}
            <Card style={{ marginBottom: 20, background: "var(--orange-50)", borderColor: "#E8CFB4" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <Icon name="trending-up" size={20} color="#9A4F0C" style={{ marginTop: 2 }} />
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14.5 }}>Commission forecast</div>
                  <p style={{ fontSize: 13.5, color: "var(--fg2)", lineHeight: 1.55, margin: "4px 0 0" }}>
                    Booking this itinerary puts Wanderlust Travel at <strong style={{ color: "var(--fg1)" }}>84% of the Q3 commission target</strong>,
                    up from 71%. Groups of this profile historically add a second Sky Dining booking within 14 days.
                  </p>
                </div>
              </div>
            </Card>

            {/* Days */}
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {resolved.map(d => (
                <Card key={d.day} pad={0}>
                  <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12 }}>
                    <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--orange-900)", background: "var(--orange-50)", padding: "4px 10px", borderRadius: "var(--radius-pill)" }}>{d.day}</span>
                    <span style={{ fontSize: 14.5, color: "var(--fg2)" }}>{d.note}</span>
                  </div>
                  {d.items.map((i, idx) => (
                    <div key={i.id} style={{ display: "flex", gap: 14, padding: 16, alignItems: "center", borderBottom: idx < d.items.length - 1 ? "1px solid var(--border)" : 0 }}>
                      <Photo src={i.photo} tint={i.img} alt={i.name} style={{ width: 96, height: 72, borderRadius: "var(--radius-md)", flex: "none", cursor: "pointer" }}><button onClick={() => onOpen(i)} aria-label={`Open ${i.name}`} style={{ position: "absolute", inset: 0, background: "none", border: 0, cursor: "pointer" }}></button></Photo>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <button onClick={() => onOpen(i)} style={{ background: "none", border: 0, padding: 0, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 600, color: "var(--fg1)", textAlign: "left" }}>{i.name}</button>
                        <div style={{ fontSize: 12.5, color: "var(--fg2)" }}>{i.partner} · {i.qty} × S${i.trade.toFixed(2)} / {i.unit}</div>
                      </div>
                      <div style={{ fontWeight: 600, width: 100, textAlign: "right" }}>S${(i.trade * i.qty).toLocaleString(undefined, { minimumFractionDigits: 2 })}</div>
                    </div>
                  ))}
                </Card>
              ))}
            </div>

            {/* Convert to purchase - S/No. 121 */}
            <Card style={{ marginTop: 20, display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
              <div style={{ flex: 1, minWidth: 240 }}>
                <div style={{ fontWeight: 600, fontSize: 16 }}>Convert this itinerary to an order</div>
                <p className="caption" style={{ margin: "4px 0 0" }}>
                  {all.length} products across {partners.length} island partners - a cross-partner bundle, settled in one transaction.
                </p>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ fontSize: 22, fontWeight: 700 }}>S${total.toLocaleString(undefined, { minimumFractionDigits: 2 })}</div>
                <div style={{ fontSize: 12, color: "var(--fg2)" }}>excludes GST</div>
              </div>
              <Btn variant="primary" icon="shopping-cart" onClick={() => onAddAll(all)}>Add all to itinerary</Btn>
            </Card>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AiItineraryScreen });
