const { useState: useStateCC, useEffect: useEffectCC, useRef: useRefCC } = React;

// A series of multiple-choice questions; after answers, asks Claude to
// recommend filters as JSON, then applies them.

const CONCIERGE_QUESTIONS = [
  { id: 'phase',
    q: 'What is this move really about?',
    opts: ['Career acceleration', 'Lifestyle upgrade', 'Cost arbitrage', 'Reinvention / sabbatical'] },
  { id: 'budget',
    q: 'What does your monthly budget look like?',
    opts: ['Under $1,500 — tight', '$1,500–3,000 — comfortable', '$3,000–6,000 — generous', '$6,000+ — unconstrained'] },
  { id: 'climate',
    q: 'Climate you come alive in?',
    opts: ['Warm and coastal', 'Tropical and lush', 'Temperate / four seasons', 'Dry / arid', 'Cold and stark'] },
  { id: 'social',
    q: 'How much scene do you want?',
    opts: ['Deep expat community', 'Small crew of serious people', 'Mostly locals, few foreigners', 'Solitude'] },
  { id: 'work',
    q: 'What kind of work matters here?',
    opts: ['Remote solo work', 'Building / fundraising', 'Creative practice', 'Not working — rest / health'] },
  { id: 'risk',
    q: 'Risk tolerance on safety vs. interestingness?',
    opts: ['Safety-first always', 'Safe-ish is fine', 'Edge is part of the appeal'] },
  { id: 'visa',
    q: 'Paperwork appetite?',
    opts: ['Must have a clear visa path', 'Open to the tourist-run lifestyle', 'Want permanent residency optionality'] },
];

function Concierge({ locations, onApplyFilters }) {
  const [open, setOpen] = useStateCC(false);
  const [step, setStep] = useStateCC(0);
  const [answers, setAnswers] = useStateCC({});
  const [recommending, setRecommending] = useStateCC(false);
  const [recommendation, setRecommendation] = useStateCC(null);

  useEffectCC(() => {
    const opener = () => setOpen(true);
    window.addEventListener('expat:open-concierge', opener);
    return () => window.removeEventListener('expat:open-concierge', opener);
  }, []);

  const total = CONCIERGE_QUESTIONS.length;
  const done = step >= total;

  const selectOpt = (opt) => {
    const q = CONCIERGE_QUESTIONS[step];
    setAnswers(a => ({ ...a, [q.id]: opt }));
    setStep(s => s + 1);
  };

  useEffectCC(() => {
    if (!done || recommendation || recommending) return;
    if (!window.claudeClient.isSignedIn() && window.claudeClient.mode() !== 'host') {
      setRecommendation({ __noKey: true });
      return;
    }
    (async () => {
      setRecommending(true);
      try {
        const answersText = CONCIERGE_QUESTIONS.map(q => `- ${q.q}  → ${answers[q.id]}`).join('\n');
        const profile = window.store?.getCurrentUser()?.profile || {};
        const bioContext = [
          profile.citizenships?.length ? `Citizenship: ${profile.citizenships.join(', ')}` : null,
          profile.companions      ? `Traveling: ${profile.companions}` : null,
          profile.pets?.length    ? `Pets: ${profile.pets.join(', ')}` : null,
          profile.profession      ? `Profession: ${profile.profession}` : null,
          profile.languages?.length ? `Languages: ${profile.languages.join(', ')}` : null,
          profile.health          ? `Health notes: ${profile.health}` : null,
          profile.lifestyle       ? `Lifestyle: ${profile.lifestyle}` : null,
        ].filter(Boolean).join('\n');

        const prompt = `You are an expat relocation concierge. Based on the user's answers and profile, return a JSON object with filter recommendations and a short human reasoning.

Allowed filter fields:
- tiers: array of ("survival" | "comfort" | "luxury")
- maxCost: number (USD/month, 800–12000)
- vibes: array of ("remote-work"|"health-wellness"|"fund-raising"|"networking"|"creative"|"foodie"|"off-beaten"|"luxury")
- biomes: array of ("mediterranean"|"temperate-atlantic"|"temperate-continental"|"temperate-humid"|"temperate-pampas"|"temperate-boreal"|"subtropical-humid"|"subtropical-coastal"|"subtropical-island"|"tropical-wet"|"tropical-dry"|"tropical-highland"|"jungle-rainforest"|"hot-desert"|"high-altitude"|"subarctic")
- minSafety: number 0-100
- minVisa: number 0-100
- minInternet: number 0-100
- minHealth: number 0-100

User profile (from their saved bio):
${bioContext || '(no profile data)'}

User concierge answers:
${answersText}

Return ONLY a JSON object with two top-level keys: "filters" (the object above) and "reasoning" (1-2 sentence string explaining your picks, conversational, referencing their specific situation). No markdown, no preamble.`;
        const res = await window.claudeClient.complete(prompt);
        // extract JSON
        const match = res.match(/\{[\s\S]*\}/);
        const json = JSON.parse(match ? match[0] : res);
        setRecommendation(json);
      } catch (e) {
        setRecommendation({ filters: {}, reasoning: 'Could not reach the concierge. Try the filters directly.' });
      }
      setRecommending(false);
    })();
  }, [done]);

  const reset = () => {
    setStep(0); setAnswers({}); setRecommendation(null);
  };

  const apply = () => {
    if (!recommendation?.filters) return;
    onApplyFilters(recommendation.filters);
    setOpen(false);
    setTimeout(reset, 300);
  };

  return (
    <>
      {open && (
        <div className="loc-card-overlay" onClick={() => setOpen(false)}>
          <div className="concierge-panel concierge-modal" onClick={e => e.stopPropagation()}>
          <div className="concierge-head">
            <div>
              <div className="compare-kicker">CONCIERGE</div>
              <div className="concierge-title">Let's narrow this down</div>
            </div>
            <button className="close-btn" onClick={() => setOpen(false)}>×</button>
          </div>

          {!done && (
            <div className="concierge-body">
              <div className="concierge-progress">
                {CONCIERGE_QUESTIONS.map((_, i) => (
                  <span key={i} className={`prog-seg ${i < step ? 'done' : i === step ? 'cur' : ''}`}/>
                ))}
              </div>
              <div className="concierge-step">
                <div className="concierge-stepnum">Q{step + 1} / {total}</div>
                <div className="concierge-q">{CONCIERGE_QUESTIONS[step].q}</div>
                <div className="concierge-opts">
                  {CONCIERGE_QUESTIONS[step].opts.map(opt => (
                    <button key={opt} className="concierge-opt" onClick={() => selectOpt(opt)}>
                      {opt}
                    </button>
                  ))}
                </div>
                {step > 0 && (
                  <button className="back-btn" onClick={() => setStep(s => s - 1)}>← back</button>
                )}
              </div>
            </div>
          )}

          {done && (
            <div className="concierge-body">
              {recommending && (
                <div className="concierge-thinking">
                  <div className="deep-loading"><span/><span/><span/></div>
                  <div>Matching your answers to hubs…</div>
                </div>
              )}
              {recommendation && !recommending && (
                recommendation.__noKey ? (
                  <div className="concierge-result">
                    <SignInForAI feature="AI Concierge"/>
                    <div className="concierge-btns" style={{ marginTop: 16 }}>
                      <button className="reset-btn" onClick={reset}>← Start over</button>
                    </div>
                  </div>
                ) : (
                <div className="concierge-result">
                  <div className="concierge-kick">CLAUDE RECOMMENDS</div>
                  <div className="concierge-reason">{recommendation.reasoning}</div>
                  <div className="concierge-filterpreview">
                    {recommendation.filters?.tiers?.length > 0 && (
                      <div><span className="cfp-lbl">Tiers:</span> {recommendation.filters.tiers.join(', ')}</div>
                    )}
                    {recommendation.filters?.vibes?.length > 0 && (
                      <div><span className="cfp-lbl">Vibes:</span> {recommendation.filters.vibes.join(', ')}</div>
                    )}
                    {recommendation.filters?.biomes?.length > 0 && (
                      <div><span className="cfp-lbl">Biomes:</span> {recommendation.filters.biomes.join(', ')}</div>
                    )}
                    {recommendation.filters?.maxCost && (
                      <div><span className="cfp-lbl">Max cost:</span> ${recommendation.filters.maxCost.toLocaleString()}/mo</div>
                    )}
                    {(recommendation.filters?.minSafety || recommendation.filters?.minVisa) && (
                      <div><span className="cfp-lbl">Thresholds:</span>
                        {recommendation.filters?.minSafety ? ` safety ≥${recommendation.filters.minSafety}` : ''}
                        {recommendation.filters?.minVisa ? ` · visa ≥${recommendation.filters.minVisa}` : ''}
                      </div>
                    )}
                  </div>
                  <div className="concierge-btns">
                    <button className="deep-btn" onClick={apply}>Apply filters →</button>
                    <button className="reset-btn" onClick={reset}>Start over</button>
                  </div>
                </div>
                )
              )}
            </div>
          )}
          </div>
        </div>
      )}
    </>
  );
}

window.Concierge = Concierge;
window.openConcierge = () => window.dispatchEvent(new CustomEvent('expat:open-concierge'));
