/* ============================================================
   INDIC LEAGUE NEWS — Onboarding (two-step)
   Step 1: choose topics (min 3)
   Step 2: political inclination — pill OR quiz OR skip
   ============================================================ */

function Onboarding({ initialTopics = [], onComplete, onStartQuiz, prefilledPosition }) {
  const [step, setStep] = React.useState(1);
  const [topics, setTopics] = React.useState(new Set(initialTopics));
  const [position, setPosition] = React.useState(prefilledPosition?.id || null);

  // If user came back from the quiz with a result, jump to step 2
  React.useEffect(() => {
    if (prefilledPosition) {
      setStep(2);
      setPosition(prefilledPosition.id);
    }
  }, [prefilledPosition]);

  const toggleTopic = (id) => {
    window.IL_Sounds && window.IL_Sounds.tap();
    window.IL_Util && window.IL_Util.Haptics.light();
    setTopics(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const goStep2 = () => {
    if (topics.size < 3) return;
    window.IL_Sounds && window.IL_Sounds.pick();
    window.IL_Util && window.IL_Util.Haptics.medium();
    setStep(2);
  };

  const goBack = () => {
    window.IL_Sounds && window.IL_Sounds.tap();
    setStep(1);
  };

  const submitFinal = (positionId = position) => {
    const selectedTopics = Array.from(topics);
    let positionVal = null;
    let method = null;
    if (positionId) {
      const opt = window.IL_POLITICAL_OPTIONS.find(o => o.id === positionId);
      if (opt) {
        positionVal = opt.position;
        method = prefilledPosition ? 'quiz' : 'self_select';
      }
    }
    window.IL_Util.Storage.set(window.IL_KEYS.topics, selectedTopics);
    window.IL_Util.Storage.set(window.IL_KEYS.political, {
      position: positionVal,
      method,
      label: window.IL_LABEL_FROM_SCORE(positionVal),
    });
    window.IL_Sounds && window.IL_Sounds.success();
    window.IL_Util && window.IL_Util.Haptics.success();
    onComplete({
      topics: selectedTopics,
      position: positionVal,
      method,
    });
  };

  const skipPolitical = () => {
    window.IL_Sounds && window.IL_Sounds.tap();
    submitFinal(null);
  };

  if (step === 1) {
    return (
      <div className="screen">
        <div className="onboard">
          <div className="onboard-top">
            <div className="steps">
              <span className="step-dot active" />
              <span className="step-dot" />
            </div>
            <span style={{ fontSize: 13, color: 'var(--text-3)', fontWeight: 600 }}>
              1 of 2
            </span>
          </div>

          <div className="onboard-eyebrow">Personalise your feed</div>
          <h1 className="onboard-heading">
            What interests <em>you?</em>
          </h1>
          <p className="onboard-sub">Choose the topics you want us to cover. Pick at least 3 to continue.</p>

          <div className="topic-grid">
            {window.IL_TOPICS.map(t => (
              <TopicPill
                key={t.id}
                topic={t}
                selected={topics.has(t.id)}
                onToggle={() => toggleTopic(t.id)}
              />
            ))}
          </div>

          <p className="onboard-hint">
            {topics.size === 0 && 'Select 3 to continue'}
            {topics.size > 0 && topics.size < 3 && `Select ${3 - topics.size} more to continue`}
            {topics.size >= 3 && topics.size < window.IL_TOPICS.length && `${topics.size} topics selected — looking good`}
            {topics.size === window.IL_TOPICS.length && 'All topics selected — your feed will be wide open'}
          </p>

          <div className="onboard-actions">
            <button
              type="button"
              className="btn"
              disabled={topics.size < 3}
              onClick={goStep2}
            >
              Continue
              <Icon name="arrow-right" size={18} stroke={2.2} color="#fff" />
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Step 2 — Political inclination
  return (
    <div className="screen">
      <div className="onboard">
        <div className="onboard-top">
          <button
            aria-label="Back"
            onClick={goBack}
            style={{
              width: 38, height: 38,
              borderRadius: 10,
              border: '1px solid var(--border-strong)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--text-1)',
            }}
          >
            <Icon name="chevron-left" size={18} stroke={2} />
          </button>
          <div className="steps">
            <span className="step-dot" />
            <span className="step-dot active" />
          </div>
          <button
            onClick={skipPolitical}
            className="onboard-skip"
          >
            Skip
          </button>
        </div>

        <div className="onboard-eyebrow">How do you see the world?</div>
        <h1 className="onboard-heading">
          Let's understand <em>your perspective</em>
        </h1>
        <p className="onboard-sub">
          This helps us show you a balanced range of stories — we won't lock you in a bubble. You can change this anytime.
        </p>

        <div className="political-list">
          {window.IL_POLITICAL_OPTIONS.map(opt => (
            <PoliticalPill
              key={opt.id}
              option={opt}
              selected={position === opt.id}
              onSelect={() => {
                window.IL_Sounds && window.IL_Sounds.pick();
                window.IL_Util && window.IL_Util.Haptics.pick();
                setPosition(opt.id);
              }}
            />
          ))}
        </div>

        <div className="or-divider">OR</div>

        <button
          type="button"
          className="btn btn-secondary"
          onClick={() => {
            window.IL_Sounds && window.IL_Sounds.tap();
            window.IL_Util && window.IL_Util.Haptics.light();
            onStartQuiz && onStartQuiz();
          }}
        >
          Take the 2-min quiz
          <Icon name="arrow-right" size={18} stroke={2.2} />
        </button>

        <p className="onboard-hint" style={{ marginTop: 20 }}>
          You'll see more stories from across the spectrum — not less of what you came for.
        </p>

        <div className="onboard-actions">
          <button
            type="button"
            className="btn"
            onClick={() => submitFinal()}
          >
            Get my feed
            <Icon name="arrow-right" size={18} stroke={2.2} color="#fff" />
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Onboarding });
