const { useState: useStateC, useRef: useRefC, useEffect: useEffectC } = React;

// NoKeyPrompt replaced by SignInForAI (defined in AuthModal.jsx, exported to window)
function NoKeyPrompt({ compact }) {
  if (compact) return (
    <span className="no-key-inline">
      <button className="no-key-link" onClick={() => window.dispatchEvent(new CustomEvent('expat:require-signin'))}>
        Sign in for AI features
      </button>
    </span>
  );
  return <SignInForAI feature="AI Deep Dive &amp; Ask"/>;
}

function StatBar({ label, val }) {
  return (
    <div className="statbar">
      <div className="statbar-row">
        <span className="statbar-label">{label}</span>
        <span className="statbar-val">{val}</span>
      </div>
      <div className="statbar-track">
        <div className="statbar-fill" style={{ width: val + '%' }} />
      </div>
    </div>
  );
}

function LocationCard({ loc, onClose, isFav, onToggleFav, onDelete, onAddToPlaybook }) {
  const [deep, setDeep] = useStateC(null);
  const [loadingDeep, setLoadingDeep] = useStateC(false);
  const [question, setQuestion] = useStateC('');
  const [qaHistory, setQaHistory] = useStateC([]);
  const [asking, setAsking] = useStateC(false);

  // Pull user bio for context
  const profile = window.store?.getCurrentUser()?.profile || {};
  const bioContext = [
    profile.companions      ? `Traveling: ${profile.companions}` : null,
    profile.budgetTier      ? `Budget tier: ${profile.budgetTier}` : null,
    profile.workSetup       ? `Work: ${profile.workSetup}` : null,
    profile.profession      ? `Profession: ${profile.profession}` : null,
    profile.citizenships?.length ? `Citizenship: ${profile.citizenships.join(', ')}` : null,
    profile.languages?.length    ? `Languages: ${profile.languages.join(', ')}` : null,
    profile.pets?.length         ? `Pets: ${profile.pets.join(', ')}` : null,
    profile.pace            ? `Pace: ${profile.pace}` : null,
    profile.health          ? `Health notes: ${profile.health}` : null,
    profile.lifestyle       ? `Lifestyle: ${profile.lifestyle}` : null,
    profile.bio             ? `About: ${profile.bio}` : null,
  ].filter(Boolean).join('\n') || 'No profile filled out.';

  const runDeepDive = async () => {
    if (!window.claudeClient.isSignedIn() && window.claudeClient.mode() !== 'host') {
      setDeep('__no_key__');
      return;
    }
    setLoadingDeep(true);
    setDeep(null);
    try {
      const prompt = `You are an expat relocation analyst writing for a discerning professional. Give a deep dive on ${loc.name}, ${loc.country} as an expat hub tailored to this specific person.

User profile:
${bioContext}

City stats: comfort budget ~$${loc.costComfort}/mo, safety ${loc.safety}/100, visa flex ${loc.visaFlex}/100, internet ${loc.internet}/100, healthcare ${loc.healthcare}/100, vibes: ${loc.vibes.join(', ')}.

Structure as 4 short paragraphs: (1) whether this city fits their specific situation and who it's NOT for, (2) cost-of-living reality at comfort tier given their companions/lifestyle, (3) visa strategy for their citizenship(s) and timeline, (4) the real downsides no one mentions in nomad blogs. Be direct, specific, and avoid clichés. ~220 words.`;
      const res = await window.claudeClient.complete(prompt);
      setDeep(res);
    } catch (e) {
      if (e.code === '__NOT_SIGNED_IN__') { setDeep('__no_key__'); }
      else if (e.code === 'QUOTA_EXCEEDED') { setDeep('__quota__:' + e.message); }
      else { setDeep('(Request failed: ' + (e.message || 'unknown') + ')'); }
    }
    setLoadingDeep(false);
  };

  const askQuestion = async () => {
    if (!question.trim()) return;
    if (!window.claudeClient.isSignedIn() && window.claudeClient.mode() !== 'host') {
      setQaHistory(h => [...h, { q: question.trim(), a: '__no_key__' }]);
      setQuestion('');
      return;
    }
    const q = question.trim();
    setQuestion('');
    setAsking(true);
    setQaHistory(h => [...h, { q, a: null }]);
    try {
      const prompt = `You are an expat advisor answering a question about ${loc.name}, ${loc.country}.

User profile:
${bioContext}

City stats: survival $${loc.costSurvival}, comfort $${loc.costComfort}, luxury $${loc.costLuxury}. Safety ${loc.safety}/100, visa flex ${loc.visaFlex}/100, internet ${loc.internet}/100. Vibes: ${loc.vibes.join(', ')}. Biome: ${loc.biome}.

Question: ${q}

Answer in 2-4 tight sentences tailored to their specific situation. Be specific and avoid fluff.`;
      const res = await window.claudeClient.complete(prompt);
      setQaHistory(h => h.map((item, i) => i === h.length - 1 ? { ...item, a: res } : item));
    } catch (e) {
      setQaHistory(h => h.map((item, i) => i === h.length - 1 ? { ...item, a: '(Request failed.)' } : item));
    }
    setAsking(false);
  };

  return (
    <div className="loc-card-overlay" onClick={onClose}>
      <div className="loc-card" onClick={e => e.stopPropagation()}>
        <div className="loc-card-head">
          <div>
            <div className="loc-kicker">
              {loc.userAdded && <span className="user-badge-inline">USER·ADDED</span>}
              {loc.country.toUpperCase()} · {loc.lat.toFixed(2)}°, {loc.lng.toFixed(2)}°
            </div>
            <h2 className="loc-name">{loc.name}</h2>
            <div className="loc-tags">
              {loc.tags.map(t => <span key={t} className="loc-tag">{t}</span>)}
            </div>
          </div>
          <div className="loc-card-actions">
            {onAddToPlaybook && (
              <button className="fav-btn add-pb-btn" onClick={onAddToPlaybook} title="Add to active playbook">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
                  <rect x="3" y="2.5" width="10" height="11" rx="1"/>
                  <line x1="8" y1="6" x2="8" y2="11"/>
                  <line x1="5.5" y1="8.5" x2="10.5" y2="8.5"/>
                </svg>
                Add to playbook
              </button>
            )}
            {loc.userAdded && onDelete && (
              <button className="fav-btn" onClick={() => { if (confirm('Delete this user-added city?')) onDelete(); }} title="Delete user city">
                delete
              </button>
            )}
            <button className={`fav-btn ${isFav ? 'on' : ''}`} onClick={onToggleFav}
              title={isFav ? 'Unfavorite' : 'Favorite to compare'}>
              <svg width="14" height="14" viewBox="0 0 16 16">
                <path d="M8 1l2.2 4.5L15 6.2l-3.5 3.4.8 4.9L8 12.2 3.7 14.5l.8-4.9L1 6.2l4.8-.7L8 1z"
                  fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/>
              </svg>
              {isFav ? 'Saved' : 'Favorite'}
            </button>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
        </div>

        <div className="loc-pitch">{loc.pitch}</div>

        <div className="loc-costs">
          <div className="cost-tier">
            <div className="cost-label">SURVIVAL</div>
            <div className="cost-val">${loc.costSurvival.toLocaleString()}<span>/mo</span></div>
          </div>
          <div className="cost-tier">
            <div className="cost-label">COMFORT</div>
            <div className="cost-val">${loc.costComfort.toLocaleString()}<span>/mo</span></div>
          </div>
          <div className="cost-tier">
            <div className="cost-label">LUXURY</div>
            <div className="cost-val">${loc.costLuxury.toLocaleString()}<span>/mo</span></div>
          </div>
        </div>

        <div className="loc-stats">
          <StatBar label="Safety" val={loc.safety} />
          <StatBar label="Visa flexibility" val={loc.visaFlex} />
          <StatBar label="Internet" val={loc.internet} />
          <StatBar label="Healthcare" val={loc.healthcare} />
          <StatBar label="English everyday" val={loc.englishOk} />
          <StatBar label="Expat community" val={loc.community} />
        </div>

        <div className="loc-ai">
          <button className="deep-btn" onClick={runDeepDive} disabled={loadingDeep}>
            <span className="ai-dot"/>
            {loadingDeep ? 'Generating…' : deep ? 'Regenerate deep dive' : 'AI Deep Dive'}
          </button>

          {(loadingDeep || deep) && (
            <div className="deep-output">
              {loadingDeep && (
                <div className="deep-loading">
                  <span/><span/><span/>
                </div>
              )}
              {deep && deep === '__no_key__' ? (
                <SignInForAI feature="AI Deep Dive"/>
              ) : deep && deep.startsWith && deep.startsWith('__quota__:') ? (
                <div className="quota-banner">{deep.replace('__quota__:', '')}</div>
              ) : deep && (
                <div className="deep-text">{deep}</div>
              )}
            </div>
          )}

          <div className="ask-row">
            <input
              className="ask-input"
              placeholder={`Ask about ${loc.name}…  e.g. best neighborhood for families`}
              value={question}
              onChange={e => setQuestion(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && !asking && askQuestion()}
              disabled={asking}
            />
            <button className="ask-btn" onClick={askQuestion} disabled={asking || !question.trim()}>
              Ask →
            </button>
          </div>

          {qaHistory.length > 0 && (
            <div className="qa-list">
              {qaHistory.map((item, i) => (
                <div key={i} className="qa-item">
                  <div className="qa-q">› {item.q}</div>
                  <div className="qa-a">
                    {item.a === null ? <span className="pulse">thinking…</span>
                     : item.a === '__no_key__' ? <NoKeyPrompt compact/>
                     : item.a}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.LocationCard = LocationCard;
