/* AI Counselor screen — scripted conversation with typing & quick replies */
const { useState, useEffect, useRef } = React;

const SCRIPT = [
  {
    id: "intro",
    ai: [
      "Hello, Khalid. I'm Atlas — your AI placement counselor at logicconnect.",
      "Are you looking to secure an internship in the logistics sector?",
    ],
    replies: [
      { value: "yes", label: "Yes, that's the plan", primary: true },
      { value: "other", label: "Tell me more first" },
    ],
  },
  {
    id: "multi",
    ai: [
      "Great. We partner with leading operators across Oman and the GCC — DHL, GAC, Asyad, MSC, plus a network of SMEs.",
      "Would you like to train at multiple companies to build a comprehensive portfolio, or focus on one?",
    ],
    replies: [
      { value: "multi", label: "Build a multi-company plan", primary: true },
      { value: "single", label: "Just one company" },
    ],
  },
  {
    id: "experience",
    ai: [
      "Got it. To calibrate the roadmap — how much prior logistics experience do you have?",
    ],
    replies: [
      { value: "none", label: "Fresh graduate", primary: true },
      { value: "internship", label: "1 short internship" },
      { value: "year+", label: "A year or more" },
    ],
  },
  {
    id: "focus",
    ai: [
      "Which area interests you most? I'll weight your placement sequence toward it — you'll still get cross-functional exposure.",
    ],
    replies: [
      { value: "freight", label: "Freight forwarding" },
      { value: "warehouse", label: "Warehousing & ops" },
      { value: "customs", label: "Customs & compliance" },
      { value: "supply", label: "Supply chain strategy" },
      { value: "open", label: "Open to all" },
    ],
  },
  {
    id: "tier",
    ai: [
      "Since you're starting fresh, I recommend a tiered progression: begin at an SME for foundational fluency, then a mid-tier operator, then graduate to a global enterprise.",
      "This builds your CV at every step instead of betting everything on one placement. Does this step-by-step approach sound good?",
    ],
    replies: [
      {
        value: "yes",
        label: "Click here to view your generated plan",
        primary: true,
        generate: true,
      },
    ],
  },
];

/* Replace label with the chosen user-friendly text */
const USER_ECHO = {
  yes: "Yes, I'm focused on logistics.",
  other: "Tell me more first.",
  multi: "Yes — let's build a multi-company plan.",
  single: "Just one company is fine.",
  none: "I'm a fresh graduate, no real experience yet.",
  internship: "I've done one short internship.",
  "year+": "A year or more.",
  freight: "Freight forwarding.",
  warehouse: "Warehousing & operations.",
  customs: "Customs & compliance.",
  supply: "Supply chain strategy.",
  open: "Open to all areas.",
};

function ChatScreen({ onComplete, accent }) {
  // turns: array of {role:'ai'|'user', lines:[...]} as they appear
  const [turns, setTurns] = useState([]);
  const [stage, setStage] = useState(0); // index in SCRIPT
  const [typing, setTyping] = useState(true);
  const [showReplies, setShowReplies] = useState(false);
  const [generating, setGenerating] = useState(false);
  const scrollRef = useRef(null);
  const mountedStage = useRef(-1);

  /* When stage changes, animate AI typing → reveal AI message → show replies */
  useEffect(() => {
    if (stage >= SCRIPT.length) return;
    if (mountedStage.current === stage) return;
    mountedStage.current = stage;

    setTyping(true);
    setShowReplies(false);

    const typingDelay = stage === 0 ? 900 : 1100;
    const t1 = setTimeout(() => {
      setTyping(false);
      setTurns((prev) => [
        ...prev,
        { role: "ai", lines: SCRIPT[stage].ai },
      ]);
      const t2 = setTimeout(() => setShowReplies(true), 280);
      return () => clearTimeout(t2);
    }, typingDelay);
    return () => clearTimeout(t1);
  }, [stage]);

  /* Autoscroll to bottom on any change */
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    el.scrollTop = el.scrollHeight;
  }, [turns, typing, showReplies, generating]);

  const handleReply = (reply) => {
    setShowReplies(false);
    setTurns((prev) => [
      ...prev,
      { role: "user", lines: [USER_ECHO[reply.value] || reply.label] },
    ]);

    if (reply.generate) {
      // Final step: show generating state then transition
      setTimeout(() => {
        setGenerating(true);
        setTurns((prev) => [
          ...prev,
          {
            role: "ai",
            generating: true,
            lines: [
              "Drafting your personalized roadmap now…",
              "Cross-referencing the OLA program catalogue, active partner companies, and your tier preferences.",
            ],
          },
        ]);
      }, 450);
      setTimeout(() => {
        onComplete && onComplete();
      }, 2400);
      return;
    }

    // Advance stage
    setTimeout(() => setStage((s) => s + 1), 380);
  };

  const stepLabels = [
    "Greeting",
    "Portfolio scope",
    "Experience level",
    "Specialization",
    "Progression plan",
  ];

  return (
    <div className="chatwrap">
      <aside className="chataside">
        <div className="label">Intake — Stage 1</div>
        {stepLabels.map((s, i) => (
          <div
            key={s}
            className={
              "step " +
              (i < stage ? "done" : i === stage ? "active" : "")
            }
          >
            <span className="num">
              {i < stage ? <Check size={12} /> : String(i + 1).padStart(2, "0")}
            </span>
            <span>{s}</span>
          </div>
        ))}
        <div style={{ marginTop: 24 }} className="label">
          Why this works
        </div>
        <p
          style={{
            fontSize: 13,
            lineHeight: 1.55,
            color: "var(--muted)",
            margin: 0,
          }}
        >
          Atlas curates a sequenced plan based on your starting point — so you
          enter the job market with a real portfolio, not a single line on your CV.
        </p>
      </aside>

      <section className="chatpanel">
        <header className="chathead">
          <div className="who">
            <span className="botbadge" />
            <div>
              <h3>Atlas</h3>
              <div className="sub">AI placement counselor · online</div>
            </div>
          </div>
          <div className="tools">
            <button className="toggle-form">
              <FileText size={13} />
              Use form instead
            </button>
          </div>
        </header>

        <div className="messages nicescroll" ref={scrollRef}>
          {turns.map((t, i) => (
            <div key={i} className={"msg-row " + (t.role === "user" ? "user" : "ai")}>
              <span className="av" />
              <div className="bubble">
                {t.role === "ai" && i === 0 && <div className="meta">Atlas</div>}
                {t.lines.map((line, j) => (
                  <div
                    key={j}
                    style={{ marginTop: j > 0 ? 8 : 0 }}
                  >
                    {line}
                  </div>
                ))}
                {t.generating && (
                  <div style={{ marginTop: 10 }}>
                    <span className="typing">
                      <span />
                      <span />
                      <span />
                    </span>
                  </div>
                )}
              </div>
            </div>
          ))}

          {typing && (
            <div className="msg-row ai">
              <span className="av" />
              <div className="bubble">
                <span className="typing">
                  <span />
                  <span />
                  <span />
                </span>
              </div>
            </div>
          )}
        </div>

        {showReplies && stage < SCRIPT.length && !generating && (
          <div className="quickreplies" key={"qr-" + stage}>
            {SCRIPT[stage].replies.map((r) => (
              <button
                key={r.value}
                className={"chip " + (r.primary ? "primary" : "")}
                onClick={() => handleReply(r)}
              >
                {r.label}
                <Chevron size={12} className="arrow" />
              </button>
            ))}
          </div>
        )}

        <footer className="chatfoot">
          <div className="chatinput">Tap a quick reply above…</div>
          <span className="hint">
            <Lock size={11} style={{ verticalAlign: -2, marginRight: 4 }} />
            Encrypted · stored as IntakeProfile
          </span>
        </footer>
      </section>
    </div>
  );
}

window.ChatScreen = ChatScreen;
