// ======== IPSProspect — prospect.jsx ========
// Deployed at prospect.ipsapp.app
// Firebase project: ipsprojectapp
// Proxy: https://api.ipsapp.app

const FIREBASE_CONFIG = {
  apiKey: "AIzaSyD47TQZsxbky1CLOh43enDwvo2Pn808ss0",
  authDomain: "ipsprojectapp.firebaseapp.com",
  projectId: "ipsprojectapp",
  storageBucket: "ipsprojectapp.firebasestorage.app",
  messagingSenderId: "683253086438",
  appId: "1:683253086438:web:d0bc67f4719e9ced76e327"
};

const APP_PIN = "8522";
const PROXY_URL = "https://api.ipsapp.app";

// ─── Firebase init ───────────────────────────────────────────────
let _db = null;
function initFirebase() {
  if (_db) return;
  try {
    if (!firebase.apps.length) firebase.initializeApp(FIREBASE_CONFIG);
    _db = firebase.firestore();
  } catch(e) { console.error("Firebase init:", e); }
}
function getDb() { return _db; }

// ─── Claude API via proxy ────────────────────────────────────────
async function callClaude(systemPrompt, userPrompt) {
  const res = await fetch(PROXY_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "claude-sonnet-4-6",
      max_tokens: 4000,
      system: systemPrompt,
      messages: [{ role: "user", content: userPrompt }]
    })
  });
  const data = await res.json();
  if (data.content && data.content[0]) return data.content[0].text;
  throw new Error("API error: " + JSON.stringify(data));
}

// ─── Firestore helpers ───────────────────────────────────────────
const COMPANY = "ipsprospect";

const DB = {
  async loadProspects() {
    if (!_db) return [];
    try {
      const snap = await _db.collection("companies").doc(COMPANY).collection("prospects").orderBy("createdAt","desc").get();
      return snap.docs.map(d => ({ id: d.id, ...d.data() }));
    } catch(e) { return []; }
  },
  async saveProspect(p) {
    if (!_db) return;
    const ref = p.id
      ? _db.collection("companies").doc(COMPANY).collection("prospects").doc(p.id)
      : _db.collection("companies").doc(COMPANY).collection("prospects").doc();
    const { id, ...data } = p;
    await ref.set({ ...data, updatedAt: Date.now() }, { merge: true });
    return ref.id;
  },
  async deleteProspect(id) {
    if (!_db) return;
    await _db.collection("companies").doc(COMPANY).collection("prospects").doc(id).delete();
  },
  async loadHuntResults() {
    if (!_db) return [];
    try {
      const snap = await _db.collection("companies").doc(COMPANY).collection("hunt_results").orderBy("huntedAt","desc").limit(50).get();
      return snap.docs.map(d => ({ id: d.id, ...d.data() }));
    } catch(e) { return []; }
  },
  async saveHuntResult(r) {
    if (!_db) return;
    const ref = _db.collection("companies").doc(COMPANY).collection("hunt_results").doc();
    await ref.set({ ...r, huntedAt: Date.now() });
    return ref.id;
  },
  async clearHuntResults() {
    if (!_db) return;
    const snap = await _db.collection("companies").doc(COMPANY).collection("hunt_results").get();
    const batch = _db.batch();
    snap.docs.forEach(d => batch.delete(d.ref));
    await batch.commit();
  },
  async deleteHuntResult(id) {
    if (!_db) return;
    await _db.collection("companies").doc(COMPANY).collection("hunt_results").doc(id).delete();
  },
  async loadAssetReports() {
    if (!_db) return [];
    try {
      const snap = await _db.collection("companies").doc(COMPANY).collection("asset_reports").orderBy("createdAt","desc").limit(50).get();
      return snap.docs.map(d => ({ id: d.id, ...d.data() }));
    } catch(e) { return []; }
  },
  async saveAssetReport(r) {
    if (!_db) return;
    const key = r.company.replace(/[^a-zA-Z0-9]/g,"_").toLowerCase();
    const ref = _db.collection("companies").doc(COMPANY).collection("asset_reports").doc(key);
    await ref.set({ ...r, createdAt: Date.now() }, { merge: false });
    return key;
  },
  async deleteAssetReport(id) {
    if (!_db) return;
    await _db.collection("companies").doc(COMPANY).collection("asset_reports").doc(id).delete();
  }
};

// ─── Status config ───────────────────────────────────────────────
const STATUSES = [
  { key: "new",       label: "New",             color: "#6366f1" },
  { key: "contacted", label: "Contacted",       color: "#f59e0b" },
  { key: "responded", label: "Responded",       color: "#3b82f6" },
  { key: "call",      label: "Call Scheduled",  color: "#8b5cf6" },
  { key: "proposal",  label: "Proposal Sent",   color: "#f97316" },
  { key: "closed",    label: "Closed ✓",        color: "#10b981" },
  { key: "dead",      label: "Dead",            color: "#6b7280" },
];

const HUNT_CATEGORIES = [
  { key: "construction", label: "🏗️ New Construction",   desc: "Produced water & brine pipeline construction permits and announcements" },
  { key: "distress",     label: "🔥 Line Distress",       desc: "Brine & produced water pipeline incidents, failures, and integrity threats" },
  { key: "contractor",   label: "👷 Contractors",         desc: "Pipeline construction companies bidding or building produced water infrastructure in TX, NM, LA" },
  { key: "swd",          label: "💧 SWD Expansion",       desc: "New saltwater disposal well permits and produced water capacity expansions" },
];

// ─── Hunt Regions ────────────────────────────────────────────────
const HUNT_REGIONS = [
  { key: "permian",      label: "Permian Basin (West TX / SE NM)",  focus: "Focus tightly on the Permian Basin — West Texas and Southeast New Mexico (counties such as Midland, Reeves, Loving, Ward, Winkler, Ector, Lea, and Eddy)." },
  { key: "southwest",    label: "Southwest (TX / NM / LA / OK)",    focus: "Focus on TX, NM, LA, OK." },
  { key: "texas",        label: "Texas (Statewide)",                focus: "Focus on Texas statewide, including the Permian Basin, Eagle Ford Shale, and East Texas basins." },
  { key: "gulf",         label: "Gulf Coast (TX / LA)",              focus: "Focus on the Gulf Coast region — Texas and Louisiana, including coastal and near-shore produced water and brine infrastructure." },
  { key: "midcon",       label: "Mid-Continent (OK / KS / N. TX)",  focus: "Focus on the Mid-Continent region — Oklahoma, Kansas, and North Texas (Anadarko and SCOOP/STACK plays)." },
  { key: "rockies",      label: "Rockies / Bakken (CO / WY / ND)",  focus: "Focus on the Rocky Mountain and Bakken region — Colorado (DJ Basin), Wyoming (Powder River Basin), and North Dakota (Bakken)." },
  { key: "appalachia",   label: "Appalachia (PA / OH / WV)",        focus: "Focus on the Appalachian Basin — Pennsylvania, Ohio, and West Virginia (Marcellus/Utica shale produced water infrastructure)." },
  { key: "nationwide",   label: "Nationwide (USA)",                 focus: "Focus nationwide across the United States, prioritizing major shale basins and regions with significant produced water, brine, or SWD pipeline infrastructure." },
  { key: "international",label: "International",                    focus: "Focus internationally, prioritizing major oil & gas producing regions outside the United States with produced water, brine, or SWD pipeline infrastructure (e.g. Canada, Middle East, Latin America). Note the country/region clearly for each lead." },
  { key: "custom",       label: "Custom Region...",                 focus: null },
];

// ─── Styles ──────────────────────────────────────────────────────
const S = {
  app: { minHeight: "100vh", background: "#0d0f12", color: "#e8ecf0", fontFamily: "'Outfit', sans-serif" },
  header: { background: "#111418", borderBottom: "1px solid #1e2330", padding: "12px 16px", display: "flex", alignItems: "center", gap: 12, position: "sticky", top: 0, zIndex: 100 },
  logo: { width: 32, height: 32, borderRadius: 6 },
  headerTitle: { fontSize: 18, fontWeight: 700, color: "#e8ecf0", letterSpacing: "-0.3px" },
  headerSub: { fontSize: 12, color: "#64748b", marginTop: 1 },
  tabs: { display: "flex", background: "#111418", borderBottom: "1px solid #1e2330", overflowX: "auto" },
  tab: (active) => ({
    padding: "14px 20px", fontSize: 13, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap",
    color: active ? "#e8ecf0" : "#64748b",
    borderBottom: active ? "2px solid #CC2222" : "2px solid transparent",
    background: "none", border: "none", borderBottom: active ? "2px solid #CC2222" : "2px solid transparent",
    transition: "color 0.15s"
  }),
  page: { padding: 16, maxWidth: 900, margin: "0 auto" },
  card: { background: "#111418", border: "1px solid #1e2330", borderRadius: 10, padding: 16, marginBottom: 12 },
  cardHeader: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 },
  label: { fontSize: 11, fontWeight: 700, color: "#64748b", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 4 },
  value: { fontSize: 14, color: "#e8ecf0" },
  input: { width: "100%", background: "#0d0f12", border: "1px solid #1e2330", borderRadius: 8, padding: "10px 12px", color: "#e8ecf0", fontSize: 14, fontFamily: "'Outfit', sans-serif", outline: "none", marginBottom: 10 },
  textarea: { width: "100%", background: "#0d0f12", border: "1px solid #1e2330", borderRadius: 8, padding: "10px 12px", color: "#e8ecf0", fontSize: 14, fontFamily: "'Outfit', sans-serif", outline: "none", marginBottom: 10, minHeight: 80, resize: "vertical" },
  select: { width: "100%", background: "#0d0f12", border: "1px solid #1e2330", borderRadius: 8, padding: "10px 12px", color: "#e8ecf0", fontSize: 14, fontFamily: "'Outfit', sans-serif", outline: "none", marginBottom: 10 },
  btn: (color="#CC2222") => ({ background: color, color: "#fff", border: "none", borderRadius: 8, padding: "10px 16px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit', sans-serif" }),
  btnOutline: { background: "none", border: "1px solid #1e2330", borderRadius: 8, padding: "8px 14px", fontSize: 13, color: "#94a3b8", cursor: "pointer", fontFamily: "'Outfit', sans-serif" },
  badge: (color) => ({ display: "inline-block", background: color + "22", color: color, border: `1px solid ${color}44`, borderRadius: 20, padding: "2px 10px", fontSize: 11, fontWeight: 700 }),
  score: (s) => {
    if (s === "hot") return { bg: "#ff4444", label: "🔥 HOT" };
    if (s === "warm") return { bg: "#f97316", label: "🟠 WARM" };
    if (s === "moderate") return { bg: "#eab308", label: "🟡 MODERATE" };
    return { bg: "#6b7280", label: "⚪ COLD" };
  },
  row: { display: "flex", gap: 10, flexWrap: "wrap" },
  col: { flex: 1, minWidth: 140 },
  divider: { borderTop: "1px solid #1e2330", margin: "12px 0" },
  pinWrap: { minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "#0d0f12" },
  pinBox: { background: "#111418", border: "1px solid #1e2330", borderRadius: 16, padding: 40, textAlign: "center", width: 320 },
  pinTitle: { fontSize: 22, fontWeight: 700, color: "#e8ecf0", marginBottom: 4 },
  pinSub: { fontSize: 13, color: "#64748b", marginBottom: 24 },
  pinInput: { width: "100%", background: "#0d0f12", border: "1px solid #1e2330", borderRadius: 8, padding: "14px", color: "#e8ecf0", fontSize: 22, textAlign: "center", letterSpacing: 8, outline: "none", marginBottom: 16, fontFamily: "'Outfit', sans-serif" },
};

// ─── PIN Screen ──────────────────────────────────────────────────
function PinScreen({ onUnlock }) {
  const [pin, setPin] = React.useState("");
  const [err, setErr] = React.useState(false);

  function tryPin(p) {
    if (p === APP_PIN) { onUnlock(); }
    else if (p.length === 4) { setErr(true); setTimeout(() => { setPin(""); setErr(false); }, 800); }
  }

  return (
    <div style={S.pinWrap}>
      <div style={S.pinBox}>
        <div style={{ fontSize: 36, marginBottom: 12 }}>🔍</div>
        <div style={S.pinTitle}>IPSProspect</div>
        <div style={S.pinSub}>Internal Pipeline Services</div>
        <input
          style={{ ...S.pinInput, borderColor: err ? "#CC2222" : "#1e2330" }}
          type="password" inputMode="numeric" maxLength={4}
          placeholder="••••" value={pin}
          onChange={e => { const v = e.target.value.replace(/\D/g,""); setPin(v); tryPin(v); }}
        />
        {err && <div style={{ color: "#CC2222", fontSize: 13, marginTop: -8, marginBottom: 8 }}>Incorrect PIN</div>}
        <div style={{ fontSize: 11, color: "#334155" }}>prospect.ipsapp.app</div>
      </div>
    </div>
  );
}

// ─── HUNT TAB ────────────────────────────────────────────────────
function HuntTab({ onAddToPipeline }) {
  const [results, setResults] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [loadingCat, setLoadingCat] = React.useState(null);
  const [savedResults, setSavedResults] = React.useState([]);
  const [showSaved, setShowSaved] = React.useState(false);
  const [removedIds, setRemovedIds] = React.useState(new Set());
  const [regionKey, setRegionKey] = React.useState("permian");
  const [customRegion, setCustomRegion] = React.useState("");

  React.useEffect(() => {
    DB.loadHuntResults().then(setSavedResults);
  }, []);

  function handleAddToPipelineAndRemove(lead) {
    // Remove from display immediately
    setRemovedIds(prev => {
      const next = new Set(prev);
      next.add(lead.huntedAt + lead.company);
      return next;
    });
    // Also remove from Firestore hunt_results if it has an id
    if (lead.id) {
      DB.deleteHuntResult(lead.id).catch(() => {});
    }
    onAddToPipeline(lead);
  }

  async function runHunt(category) {
    setLoading(true);
    setLoadingCat(category.key);
    const cat = HUNT_CATEGORIES.find(c => c.key === category.key);
    const regionCfg = HUNT_REGIONS.find(r => r.key === regionKey) || HUNT_REGIONS[0];
    const regionFocus = regionCfg.key === "custom"
      ? (customRegion.trim() ? `Focus on the following region: ${customRegion.trim()}.` : "Focus on TX, NM, LA, OK.")
      : regionCfg.focus;
    const regionLabel = regionCfg.key === "custom" ? (customRegion.trim() || "Custom") : regionCfg.label;

    const system = `You are a business development intelligence agent for Internal Pipeline Services (IPS), a specialty contractor based in Venus/Mansfield, Texas. IPS offers in-situ pipeline internal cleaning (to NACE No. 2 standard) and epoxy lining services, accessing only both ends of a line, working up to 20 miles per run. Their highest-priority targets are produced water, brine, and saltwater disposal (SWD) pipelines — these are highly corrosive and prime rehabilitation or pre-lining candidates.

Your job is to find REAL, SPECIFIC, ACTIONABLE intelligence about: ${cat.desc}

Return a JSON array of 4-6 lead objects. Each object must have:
- "company": company name
- "headline": specific finding (1 sentence, mention real details if possible)
- "source": where this would be found (e.g. "Texas RRC", "PHMSA", "Press Release", "LinkedIn")
- "location": state/region
- "score": "hot" | "warm" | "moderate" | "cold"
- "scoreReason": 1 sentence why this score
- "triggerEvent": the specific event that makes them a prospect now
- "targetTitle": best job title to contact at this company
- "linkedinSearch": a LinkedIn search string to find the right contact
- "outreachAngle": 1-2 sentences on how IPS should approach this specific lead
- "pipelineLength": line length if known or estimable from permit/filing data (e.g. "~8 miles", "12,000 ft") — use "unknown" if no data available
- "pipelineDiameter": pipe diameter (e.g. "8-inch", "12-inch") — use "unknown" if not found
- "pipelineMaterial": pipe material ("steel", "HDPE", "poly", "fiberglass") — use "unknown" if not found
- "pipelineFluid": what the line carries ("produced water", "brine", "saltwater disposal", "crude") — infer from context if needed
- "pipelineNotes": any additional specifics — age, condition, corrosion history, install year, operating pressure, coating status, or anything relevant from filings/news. Leave empty string if nothing found.

${regionFocus} Prioritize produced water, brine, SWD operators. Be specific and realistic — these should feel like real leads a BD person would act on. For pipeline specs, pull from permit filings, PHMSA records, press releases, or make an informed estimate based on typical infrastructure for that operator type and region — note if it is an estimate.

Return ONLY valid JSON array, no markdown, no explanation.`;

    const user = `Find current ${cat.label} leads for IPS pipeline cleaning and epoxy lining services in the following region: ${regionLabel}. Today's date: ${new Date().toLocaleDateString()}. Focus on the most actionable opportunities in the last 30-60 days.`;

    try {
      const text = await callClaude(system, user);
      const clean = text.replace(/```json|```/g, "").trim();
      const leads = JSON.parse(clean);
      const withMeta = leads.map(l => ({ ...l, category: category.key, categoryLabel: category.label, huntRegion: regionCfg.key, huntRegionLabel: regionLabel, huntedAt: Date.now() }));
      
      // Save to Firestore
      for (const lead of withMeta) {
        await DB.saveHuntResult(lead);
      }
      
      setResults(prev => [...withMeta, ...prev]);
      setSavedResults(prev => [...withMeta, ...prev]);
    } catch(e) {
      console.error(e);
      alert("Hunt error: " + e.message);
    }
    setLoading(false);
    setLoadingCat(null);
  }

  async function clearResults() {
    if (!confirm("Clear all saved hunt results?")) return;
    await DB.clearHuntResults();
    setSavedResults([]);
    setResults([]);
  }

  const display = (showSaved ? savedResults : results).filter(lead => {
    const key = (lead.huntedAt || "") + lead.company;
    return !removedIds.has(key);
  });

  return (
    <div style={S.page}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 4 }}>Intelligence Hunt</div>
        <div style={{ fontSize: 13, color: "#64748b" }}>Run targeted searches to surface pipeline prospects. Each hunt uses AI to identify actionable leads.</div>
      </div>

      {/* Region selector */}
      <div style={{ marginBottom: 16 }}>
        <div style={S.label}>Hunt Region</div>
        <select
          style={S.select}
          value={regionKey}
          disabled={loading}
          onChange={e => setRegionKey(e.target.value)}
        >
          {HUNT_REGIONS.map(r => (
            <option key={r.key} value={r.key}>{r.label}</option>
          ))}
        </select>
        {regionKey === "custom" && (
          <input
            style={S.input}
            value={customRegion}
            disabled={loading}
            onChange={e => setCustomRegion(e.target.value)}
            placeholder="e.g. West Virginia, or Alberta Canada, or Middle East"
          />
        )}
      </div>

      {/* Hunt buttons */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 20 }}>
        {HUNT_CATEGORIES.map(cat => (
          <button key={cat.key} style={{ ...S.btn("#111418"), border: "1px solid #1e2330", textAlign: "left", padding: 14, borderRadius: 10, opacity: loading ? 0.6 : 1 }}
            disabled={loading}
            onClick={() => runHunt(cat)}>
            <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4, color: "#e8ecf0" }}>{cat.label}</div>
            <div style={{ fontSize: 11, color: "#64748b", lineHeight: 1.4 }}>{cat.desc}</div>
            {loadingCat === cat.key && <div style={{ marginTop: 8, fontSize: 11, color: "#CC2222" }}>Hunting...</div>}
          </button>
        ))}
      </div>

      {/* Run all */}
      <div style={{ display: "flex", gap: 10, marginBottom: 20, flexWrap: "wrap" }}>
        <button style={{ ...S.btn(), flex: 1 }} disabled={loading}
          onClick={() => HUNT_CATEGORIES.forEach((c, i) => setTimeout(() => runHunt(c), i * 15000))}>
          {loading ? "Hunting..." : "🚀 Run All Hunts"}
        </button>
        <button style={{ ...S.btnOutline }} onClick={() => setShowSaved(!showSaved)}>
          {showSaved ? "Show Session" : `Show Saved (${savedResults.length})`}
        </button>
        {savedResults.length > 0 && (
          <button style={{ ...S.btnOutline, color: "#CC2222" }} onClick={clearResults}>Clear All</button>
        )}
      </div>

      {/* Results */}
      {display.length === 0 && !loading && (
        <div style={{ textAlign: "center", padding: 60, color: "#334155" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>🔍</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>No results yet</div>
          <div style={{ fontSize: 13 }}>Run a hunt above to surface pipeline prospects</div>
        </div>
      )}

      {display.map((lead, i) => {
        const sc = S.score(lead.score);
        const hasSpecs = lead.pipelineLength || lead.pipelineDiameter || lead.pipelineMaterial || lead.pipelineFluid;
        return (
          <div key={i} style={S.card}>
            <div style={S.cardHeader}>
              <div>
                <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>{lead.company}</div>
                <div style={{ fontSize: 12, color: "#64748b" }}>{lead.categoryLabel} · {lead.location} · {lead.source}{lead.huntRegionLabel ? ` · ${lead.huntRegionLabel}` : ""}</div>
              </div>
              <div style={{ ...S.badge(sc.bg), fontSize: 12 }}>{sc.label}</div>
            </div>
            <div style={{ fontSize: 13, color: "#cbd5e1", marginBottom: 10, lineHeight: 1.5 }}>{lead.headline}</div>
            <div style={S.divider} />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
              <div>
                <div style={S.label}>Trigger Event</div>
                <div style={{ ...S.value, fontSize: 13 }}>{lead.triggerEvent}</div>
              </div>
              <div>
                <div style={S.label}>Target Contact</div>
                <div style={{ ...S.value, fontSize: 13 }}>{lead.targetTitle}</div>
              </div>
            </div>

            {/* Pipeline Specs — Fix 1 */}
            {hasSpecs && (
              <div style={{ background: "#0a0c10", border: "1px solid #1e2330", borderRadius: 8, padding: "10px 12px", marginBottom: 10 }}>
                <div style={{ ...S.label, marginBottom: 6, color: "#CC2222" }}>🔩 Pipeline Specs</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
                  {lead.pipelineFluid && lead.pipelineFluid !== "unknown" && (
                    <div><div style={{ fontSize: 10, color: "#475569", textTransform: "uppercase", letterSpacing: "0.06em" }}>Fluid</div><div style={{ fontSize: 13, color: "#e8ecf0" }}>{lead.pipelineFluid}</div></div>
                  )}
                  {lead.pipelineLength && lead.pipelineLength !== "unknown" && (
                    <div><div style={{ fontSize: 10, color: "#475569", textTransform: "uppercase", letterSpacing: "0.06em" }}>Length</div><div style={{ fontSize: 13, color: "#e8ecf0" }}>{lead.pipelineLength}</div></div>
                  )}
                  {lead.pipelineDiameter && lead.pipelineDiameter !== "unknown" && (
                    <div><div style={{ fontSize: 10, color: "#475569", textTransform: "uppercase", letterSpacing: "0.06em" }}>Diameter</div><div style={{ fontSize: 13, color: "#e8ecf0" }}>{lead.pipelineDiameter}</div></div>
                  )}
                  {lead.pipelineMaterial && lead.pipelineMaterial !== "unknown" && (
                    <div><div style={{ fontSize: 10, color: "#475569", textTransform: "uppercase", letterSpacing: "0.06em" }}>Material</div><div style={{ fontSize: 13, color: "#e8ecf0" }}>{lead.pipelineMaterial}</div></div>
                  )}
                </div>
                {lead.pipelineNotes && lead.pipelineNotes.trim() && (
                  <div style={{ marginTop: 6, fontSize: 11, color: "#64748b", lineHeight: 1.4 }}>{lead.pipelineNotes}</div>
                )}
              </div>
            )}

            <div style={{ marginBottom: 10 }}>
              <div style={S.label}>Outreach Angle</div>
              <div style={{ fontSize: 13, color: "#94a3b8", lineHeight: 1.5 }}>{lead.outreachAngle}</div>
            </div>
            <div style={{ marginBottom: 12 }}>
              <div style={S.label}>LinkedIn Search</div>
              <div style={{ fontSize: 12, color: "#6366f1", fontFamily: "monospace" }}>{lead.linkedinSearch}</div>
            </div>
            <button style={{ ...S.btn(), fontSize: 12, padding: "8px 14px" }}
              onClick={() => handleAddToPipelineAndRemove(lead)}>
              + Add to Pipeline
            </button>
          </div>
        );
      })}
    </div>
  );
}

// ─── OUTREACH TAB ────────────────────────────────────────────────
function OutreachTab({ pendingLead, onClearPending }) {
  const [mode, setMode] = React.useState("profile"); // profile | lead
  const [input, setInput] = React.useState("");
  const [result, setResult] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (pendingLead) {
      setMode("lead");
      setInput(JSON.stringify(pendingLead, null, 2));
    }
  }, [pendingLead]);

  async function generate() {
    if (!input.trim()) return;
    setLoading(true);
    setResult(null);

    const system = `You are a business development assistant for Internal Pipeline Services (IPS), a specialty contractor in Venus/Mansfield, Texas. IPS cleans and epoxy-lines pipelines in place — accessing only both ends, no excavation, up to 20 miles per run. They work primarily on produced water, brine, and saltwater disposal pipelines in TX, NM, LA, and OK.

Key proof point: IPS recently completed a Mont Belvieu, TX produced water line — 3,194 ft, 24-inch, cleaned to NACE No. 2, 57 pig runs, then epoxy lined in place.

The goal of ALL outreach is simple and singular: start a genuine conversation and ask about their current internal coating program for new construction or existing infrastructure. Messages should feel human and professional — NOT sales-y, NOT generic, NOT overly flattering.

Rules for every message:
- Lightly reference 1 specific thing about the lead (their company's activity, a recent project, their region, their pipeline type) — just enough to show you did your homework, but don't dwell on it
- Keep it brief. Connection requests under 250 chars. Follow-ups 3-4 sentences max. Emails 4-5 sentences max.
- End with a soft, low-pressure ask: something like "curious what your current approach is for internal coating on new lines or existing infrastructure" or "do you have an internal coating program in place for your produced water lines?"
- NEVER use phrases like: "I came across your profile", "I couldn't help but notice", "I wanted to reach out", "I hope this message finds you well", "I'm excited to", "game-changer", "innovative solution"
- Write like a real person talking to another real person in the oil and gas industry

Generate and return JSON with:
- "score": "hot" | "warm" | "moderate" | "cold"
- "scoreReason": 1-2 sentences on why this is a good IPS prospect
- "connectionRequest": LinkedIn connection request — brief, natural, under 250 chars, no pitch
- "followUp": message to send after they connect — 3-4 sentences, light reference to their situation, ends with a question about their coating program
- "emailSubject": short, plain subject line — not clickbait, sounds like a real email
- "emailBody": 4-5 sentence cold email — references their specific context briefly, then asks about their internal coating program
- "talkingPoints": array of 3-4 practical discovery call questions (not selling points — actual questions you'd ask to understand their situation)
- "caseStudyMatch": one sentence on why the Mont Belvieu job is relevant to this prospect

Return ONLY valid JSON, no markdown.`;

    const user = mode === "profile"
      ? `Analyze this LinkedIn profile and generate personalized IPS outreach:\n\n${input}`
      : `Generate personalized IPS outreach for this hunt lead:\n\n${input}`;

    try {
      const text = await callClaude(system, user);
      const clean = text.replace(/```json|```/g, "").trim();
      setResult(JSON.parse(clean));
    } catch(e) {
      alert("Error generating outreach. Try again.");
    }
    setLoading(false);
    if (pendingLead) onClearPending();
  }

  function copy(text) {
    navigator.clipboard.writeText(text).then(() => {
      alert("Copied to clipboard");
    });
  }

  const sc = result ? S.score(result.score) : null;

  return (
    <div style={S.page}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 4 }}>Outreach Generator</div>
        <div style={{ fontSize: 13, color: "#64748b" }}>Paste a LinkedIn profile or a hunt lead — get personalized, ready-to-send messages.</div>
      </div>

      {/* Mode selector */}
      <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
        {[["profile","LinkedIn Profile"], ["lead","Hunt Lead"]].map(([k,l]) => (
          <button key={k} style={{ ...S.btn(mode===k ? "#CC2222" : "#1a1e26"), border: "1px solid #1e2330", padding: "8px 16px", fontSize: 13 }}
            onClick={() => { setMode(k); setInput(""); setResult(null); if(pendingLead) onClearPending(); }}>
            {l}
          </button>
        ))}
      </div>

      <textarea style={S.textarea}
        placeholder={mode === "profile"
          ? "Paste LinkedIn profile text here (copy from their profile page)..."
          : "Paste hunt lead data or describe the company and trigger event..."}
        value={input}
        onChange={e => setInput(e.target.value)}
        rows={6}
      />

      <button style={{ ...S.btn(), width: "100%", marginBottom: 20 }} disabled={loading || !input.trim()} onClick={generate}>
        {loading ? "Generating..." : "Generate Outreach Package"}
      </button>

      {result && (
        <div>
          {/* Score */}
          <div style={{ ...S.card, display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ ...S.badge(sc.bg), fontSize: 14, padding: "4px 14px" }}>{sc.label}</div>
            <div style={{ fontSize: 13, color: "#94a3b8", flex: 1 }}>{result.scoreReason}</div>
          </div>

          {/* Connection Request */}
          <div style={S.card}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <div style={{ fontSize: 14, fontWeight: 700 }}>LinkedIn Connection Request</div>
              <button style={S.btnOutline} onClick={() => copy(result.connectionRequest)}>Copy</button>
            </div>
            <div style={{ fontSize: 13, color: "#cbd5e1", lineHeight: 1.6, background: "#0d0f12", padding: 12, borderRadius: 8 }}>{result.connectionRequest}</div>
            <div style={{ fontSize: 11, color: "#334155", marginTop: 6 }}>{result.connectionRequest?.length || 0} / 300 characters</div>
          </div>

          {/* Follow-up */}
          <div style={S.card}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <div style={{ fontSize: 14, fontWeight: 700 }}>Follow-Up Message (after they connect)</div>
              <button style={S.btnOutline} onClick={() => copy(result.followUp)}>Copy</button>
            </div>
            <div style={{ fontSize: 13, color: "#cbd5e1", lineHeight: 1.6, background: "#0d0f12", padding: 12, borderRadius: 8 }}>{result.followUp}</div>
          </div>

          {/* Email */}
          <div style={S.card}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <div style={{ fontSize: 14, fontWeight: 700 }}>Cold Email</div>
              <button style={S.btnOutline} onClick={() => copy(`Subject: ${result.emailSubject}\n\n${result.emailBody}`)}>Copy</button>
            </div>
            <div style={{ fontSize: 12, color: "#6366f1", marginBottom: 8 }}>Subject: {result.emailSubject}</div>
            <div style={{ fontSize: 13, color: "#cbd5e1", lineHeight: 1.6, background: "#0d0f12", padding: 12, borderRadius: 8 }}>{result.emailBody}</div>
          </div>

          {/* Talking Points */}
          <div style={S.card}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10 }}>Discovery Call Talking Points</div>
            {(result.talkingPoints || []).map((pt, i) => (
              <div key={i} style={{ display: "flex", gap: 10, marginBottom: 8 }}>
                <div style={{ color: "#CC2222", fontWeight: 700, minWidth: 20 }}>{i+1}.</div>
                <div style={{ fontSize: 13, color: "#cbd5e1", lineHeight: 1.5 }}>{pt}</div>
              </div>
            ))}
          </div>

          {/* Case Study */}
          <div style={S.card}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 6 }}>Case Study to Reference</div>
            <div style={{ fontSize: 13, color: "#94a3b8", lineHeight: 1.5 }}>{result.caseStudyMatch}</div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── PIPELINE TAB ────────────────────────────────────────────────
function PipelineTab({ newProspect, onClearNew, onGenerateOutreach }) {
  const [prospects, setProspects] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showForm, setShowForm] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [filterStatus, setFilterStatus] = React.useState("all");
  const [search, setSearch] = React.useState("");

  const blank = { company:"", contactName:"", contactTitle:"", source:"Hunt", triggerEvent:"", status:"new", notes:"", nextFollowUp:"", location:"", linkedinSearch:"", outreachHistory:"" };
  const [form, setForm] = React.useState(blank);

  React.useEffect(() => {
    DB.loadProspects().then(p => { setProspects(p); setLoading(false); });
  }, []);

  React.useEffect(() => {
    if (newProspect) {
      const data = {
        ...blank,
        company: newProspect.company || "",
        contactTitle: newProspect.targetTitle || "",
        source: newProspect.categoryLabel || "Hunt",
        triggerEvent: newProspect.triggerEvent || "",
        location: newProspect.location || "",
        linkedinSearch: newProspect.linkedinSearch || "",
        notes: [
          newProspect.outreachAngle || "",
          newProspect.pipelineLength && newProspect.pipelineLength !== "unknown" ? `Length: ${newProspect.pipelineLength}` : "",
          newProspect.pipelineDiameter && newProspect.pipelineDiameter !== "unknown" ? `Diameter: ${newProspect.pipelineDiameter}` : "",
          newProspect.pipelineMaterial && newProspect.pipelineMaterial !== "unknown" ? `Material: ${newProspect.pipelineMaterial}` : "",
          newProspect.pipelineFluid && newProspect.pipelineFluid !== "unknown" ? `Fluid: ${newProspect.pipelineFluid}` : "",
          newProspect.pipelineNotes || "",
        ].filter(Boolean).join("\n"),
        status: "new",
        score: newProspect.score || "moderate",
        createdAt: Date.now()
      };
      // Auto-save directly — no form interaction needed
      DB.saveProspect(data).then(id => {
        setProspects(prev => [{ id, ...data }, ...prev]);
      });
      onClearNew();
    }
  }, [newProspect]);

  function copyProspect(p) {
    const lines = [
      `Company: ${p.company}`,
      p.location ? `Location: ${p.location}` : null,
      p.contactName ? `Contact: ${p.contactName}${p.contactTitle ? ` — ${p.contactTitle}` : ""}` : null,
      p.status ? `Status: ${STATUSES.find(s=>s.key===p.status)?.label || p.status}` : null,
      p.triggerEvent ? `Trigger: ${p.triggerEvent}` : null,
      p.linkedinSearch ? `LinkedIn Search: ${p.linkedinSearch}` : null,
      p.nextFollowUp ? `Follow-Up: ${p.nextFollowUp}` : null,
      p.notes ? `Notes: ${p.notes}` : null,
    ].filter(Boolean).join("\n");
    navigator.clipboard.writeText(lines).catch(() => {});
  }

  async function save() {
    if (!form.company.trim()) return alert("Company name required");
    const data = { ...form, createdAt: form.createdAt || Date.now() };
    if (editing) {
      await DB.saveProspect({ id: editing, ...data });
      setProspects(prev => prev.map(p => p.id === editing ? { id: editing, ...data } : p));
    } else {
      const id = await DB.saveProspect(data);
      setProspects(prev => [{ id, ...data }, ...prev]);
    }
    setShowForm(false);
    setEditing(null);
    setForm(blank);
  }

  async function del(id) {
    if (!confirm("Delete this prospect?")) return;
    await DB.deleteProspect(id);
    setProspects(prev => prev.filter(p => p.id !== id));
  }

  function edit(p) {
    setForm(p);
    setEditing(p.id);
    setShowForm(true);
  }

  async function updateStatus(id, status) {
    await DB.saveProspect({ id, status });
    setProspects(prev => prev.map(p => p.id === id ? { ...p, status } : p));
  }

  // Dashboard counts
  const hot = prospects.filter(p => p.score === "hot").length;
  const today = new Date().toISOString().slice(0,10);
  const followUps = prospects.filter(p => p.nextFollowUp && p.nextFollowUp <= today && p.status !== "closed" && p.status !== "dead").length;
  const calls = prospects.filter(p => p.status === "call").length;
  const proposals = prospects.filter(p => p.status === "proposal").length;

  // Filter
  let filtered = prospects;
  if (filterStatus !== "all") filtered = filtered.filter(p => p.status === filterStatus);
  if (search.trim()) filtered = filtered.filter(p =>
    p.company?.toLowerCase().includes(search.toLowerCase()) ||
    p.contactName?.toLowerCase().includes(search.toLowerCase()) ||
    p.triggerEvent?.toLowerCase().includes(search.toLowerCase())
  );

  // Follow-up due highlight
  function isOverdue(p) { return p.nextFollowUp && p.nextFollowUp <= today && p.status !== "closed" && p.status !== "dead"; }

  return (
    <div style={S.page}>
      {/* Dashboard */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 16 }}>
        {[
          { label: "Total", value: prospects.length, color: "#6366f1" },
          { label: "🔥 Hot", value: hot, color: "#CC2222" },
          { label: "Follow Up Today", value: followUps, color: "#f59e0b" },
          { label: "Calls Scheduled", value: calls, color: "#8b5cf6" },
        ].map(s => (
          <div key={s.label} style={{ ...S.card, textAlign: "center", padding: 12 }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: s.color }}>{s.value}</div>
            <div style={{ fontSize: 10, color: "#64748b", marginTop: 2 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* Controls */}
      <div style={{ display: "flex", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
        <input style={{ ...S.input, flex: 1, minWidth: 160, marginBottom: 0 }} placeholder="Search prospects..." value={search} onChange={e => setSearch(e.target.value)} />
        <button style={S.btn()} onClick={() => { setForm(blank); setEditing(null); setShowForm(true); }}>+ Add Prospect</button>
      </div>

      {/* Status filter */}
      <div style={{ display: "flex", gap: 6, marginBottom: 16, overflowX: "auto", paddingBottom: 4 }}>
        {[{key:"all",label:"All",color:"#64748b"}, ...STATUSES].map(s => (
          <button key={s.key} style={{ ...S.btnOutline, whiteSpace: "nowrap", fontSize: 11, padding: "5px 10px", borderColor: filterStatus===s.key ? s.color : "#1e2330", color: filterStatus===s.key ? s.color : "#64748b" }}
            onClick={() => setFilterStatus(s.key)}>{s.label}</button>
        ))}
      </div>

      {/* Form */}
      {showForm && (
        <div style={{ ...S.card, border: "1px solid #CC2222" }}>
          <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 14 }}>{editing ? "Edit Prospect" : "New Prospect"}</div>
          <div style={S.row}>
            <div style={S.col}>
              <div style={S.label}>Company *</div>
              <input style={S.input} value={form.company} onChange={e => setForm(f=>({...f,company:e.target.value}))} placeholder="Company name" />
            </div>
            <div style={S.col}>
              <div style={S.label}>Location</div>
              <input style={S.input} value={form.location} onChange={e => setForm(f=>({...f,location:e.target.value}))} placeholder="TX / Permian Basin" />
            </div>
          </div>
          <div style={S.row}>
            <div style={S.col}>
              <div style={S.label}>Contact Name</div>
              <input style={S.input} value={form.contactName} onChange={e => setForm(f=>({...f,contactName:e.target.value}))} placeholder="John Smith" />
            </div>
            <div style={S.col}>
              <div style={S.label}>Contact Title</div>
              <input style={S.input} value={form.contactTitle} onChange={e => setForm(f=>({...f,contactTitle:e.target.value}))} placeholder="Integrity Engineer" />
            </div>
          </div>
          <div style={S.row}>
            <div style={S.col}>
              <div style={S.label}>Source</div>
              <select style={S.select} value={form.source} onChange={e => setForm(f=>({...f,source:e.target.value}))}>
                {["Hunt","LinkedIn","Referral","Conference","Cold Outreach","Other"].map(s => <option key={s}>{s}</option>)}
              </select>
            </div>
            <div style={S.col}>
              <div style={S.label}>Status</div>
              <select style={S.select} value={form.status} onChange={e => setForm(f=>({...f,status:e.target.value}))}>
                {STATUSES.map(s => <option key={s.key} value={s.key}>{s.label}</option>)}
              </select>
            </div>
          </div>
          <div style={S.label}>Trigger Event</div>
          <input style={S.input} value={form.triggerEvent} onChange={e => setForm(f=>({...f,triggerEvent:e.target.value}))} placeholder="What made them a prospect?" />
          <div style={S.label}>LinkedIn Search</div>
          <input style={S.input} value={form.linkedinSearch} onChange={e => setForm(f=>({...f,linkedinSearch:e.target.value}))} placeholder="LinkedIn search string" />
          <div style={S.label}>Next Follow-Up Date</div>
          <input style={S.input} type="date" value={form.nextFollowUp} onChange={e => setForm(f=>({...f,nextFollowUp:e.target.value}))} />
          <div style={S.label}>Notes</div>
          <textarea style={S.textarea} value={form.notes} onChange={e => setForm(f=>({...f,notes:e.target.value}))} placeholder="Notes, outreach history, responses..." />
          <div style={{ display: "flex", gap: 8 }}>
            <button style={S.btn()} onClick={save}>Save</button>
            <button style={S.btnOutline} onClick={() => { setShowForm(false); setEditing(null); }}>Cancel</button>
          </div>
        </div>
      )}

      {/* List */}
      {loading && <div style={{ textAlign:"center", padding: 40, color: "#64748b" }}>Loading...</div>}

      {!loading && filtered.length === 0 && (
        <div style={{ textAlign: "center", padding: 60, color: "#334155" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>📋</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>No prospects yet</div>
          <div style={{ fontSize: 13 }}>Add prospects manually or use Hunt to surface leads</div>
        </div>
      )}

      {filtered.map(p => {
        const st = STATUSES.find(s => s.key === p.status) || STATUSES[0];
        const overdue = isOverdue(p);
        return (
          <div key={p.id} style={{ ...S.card, borderLeft: overdue ? "3px solid #f59e0b" : `3px solid ${st.color}` }}>
            <div style={S.cardHeader}>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <div style={{ fontSize: 15, fontWeight: 700 }}>{p.company}</div>
                  <div style={S.badge(st.color)}>{st.label}</div>
                  {overdue && <div style={S.badge("#f59e0b")}>⚠️ Follow Up Due</div>}
                </div>
                {p.contactName && <div style={{ fontSize: 12, color: "#64748b", marginTop: 2 }}>{p.contactName} · {p.contactTitle}</div>}
                {p.location && <div style={{ fontSize: 11, color: "#475569", marginTop: 1 }}>{p.location}</div>}
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <button style={{ ...S.btnOutline, fontSize: 11, padding: "5px 10px" }} onClick={() => onGenerateOutreach(p)}>Outreach</button>
                <button style={{ ...S.btnOutline, fontSize: 11, padding: "5px 10px" }} onClick={() => edit(p)}>Edit</button>
                <button style={{ ...S.btnOutline, fontSize: 11, padding: "5px 10px", color: "#6366f1" }} onClick={() => copyProspect(p)}>Copy</button>
                <button style={{ ...S.btnOutline, fontSize: 11, padding: "5px 10px", color: "#CC2222" }} onClick={() => del(p.id)}>✕</button>
              </div>
            </div>
            {p.triggerEvent && (
              <div style={{ fontSize: 12, color: "#94a3b8", marginBottom: 8, padding: "6px 10px", background: "#0d0f12", borderRadius: 6 }}>
                ⚡ {p.triggerEvent}
              </div>
            )}
            {p.notes && <div style={{ fontSize: 12, color: "#64748b", marginBottom: 8 }}>{p.notes}</div>}
            {p.nextFollowUp && <div style={{ fontSize: 11, color: overdue ? "#f59e0b" : "#475569" }}>📅 Follow up: {p.nextFollowUp}</div>}

            {/* Quick status update */}
            <div style={{ marginTop: 10, display: "flex", gap: 4, flexWrap: "wrap" }}>
              {STATUSES.map(s => (
                <button key={s.key}
                  style={{ fontSize: 10, padding: "3px 8px", borderRadius: 20, border: `1px solid ${p.status===s.key ? s.color : "#1e2330"}`, background: p.status===s.key ? s.color+"22" : "none", color: p.status===s.key ? s.color : "#475569", cursor: "pointer" }}
                  onClick={() => updateStatus(p.id, s.key)}>{s.label}</button>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── CONTACTS TAB ────────────────────────────────────────────────
function ContactsTab() {
  const [company, setCompany] = React.useState("");
  const [result, setResult] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [loadingStage, setLoadingStage] = React.useState("");
  const [copied, setCopied] = React.useState(null);

  function copyText(text, key) {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(key);
      setTimeout(() => setCopied(null), 1500);
    });
  }

  async function hunt() {
    if (!company.trim()) return;
    setLoading(true);
    setResult(null);

    // ── Stage 1: web search to find real named individuals ──
    setLoadingStage("Searching for real contacts...");

    const system = `You are a B2B contact intelligence agent for Internal Pipeline Services (IPS), a pipeline cleaning and epoxy coating contractor. IPS targets integrity engineers, corrosion managers, and pipeline operations managers at midstream operators, SWD operators, and produced water companies.

Use web search to find REAL, NAMED individuals currently working at the target company in pipeline operations, integrity, corrosion, or engineering roles. Search LinkedIn, company press releases, conference speaker bios, industry publications, regulatory filings, and news articles.

CRITICAL EMAIL RULE: Only include an email if you find it explicitly published somewhere on the web (company website, press release, conference listing, regulatory doc, etc.). Do NOT infer, guess, or construct emails from name patterns. If no published email is found, set email to null.

Return JSON with:
- "company": company name
- "companyType": type (Midstream Operator, SWD Operator, Pipeline Constructor, etc.)
- "relevance": why relevant to IPS pipeline cleaning/epoxy services (2 sentences)
- "contacts": array of 3-5 contacts, each with:
  - "name": REAL full name if found, or null if not found
  - "title": actual job title
  - "priority": "primary" | "secondary"
  - "email": ONLY if explicitly published on the web — otherwise null. No guessing, no patterns.
  - "emailSource": URL or publication where the email was found, or null
  - "nameSource": where the name was found (e.g. "LinkedIn", "Press Release", "Conference Bio", "Regulatory Filing") or "Title match — name not found"
  - "linkedinUrl": direct LinkedIn profile URL if found, or null
  - "linkedinSearch": search string to find them on LinkedIn
  - "why": why target this role for IPS (1 sentence)
  - "approach": personalized outreach angle based on their specific role/company situation

Return ONLY valid JSON, no markdown.`;

    const user = `You are searching for real contact information at "${company}". Run multiple searches:

1. Search: "${company}" pipeline integrity OR corrosion OR operations manager — find named employees
2. Search: "${company}" site:linkedin.com/in — find LinkedIn profiles of employees  
3. Search: "${company}" "@" email contact pipeline OR integrity OR engineering — find any published email addresses
4. Search: "${company}" press release OR news spokesperson contact — find press contacts with emails
5. Fetch their company website leadership/team/contact page directly if you can find the URL

For any real email address you find explicitly published (in a press release, on their website, in a regulatory filing, in a conference bio), include it. If no email is published anywhere, set email to null — do not construct or guess one.

Focus on TX/NM/LA/OK operations roles. Return the JSON now.`;

    try {
      const messages = [{ role: "user", content: user }];
      let finalText = null;
      for (let turn = 0; turn < 8; turn++) {
        const res = await fetch(PROXY_URL, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            model: "claude-sonnet-4-6",
            max_tokens: 4000,
            system,
            messages,
            tools: [{ type: "web_search_20250305", name: "web_search" }]
          })
        });
        const data = await res.json();
        if (!data.content) throw new Error("Empty response");
        messages.push({ role: "assistant", content: data.content });
        const textBlock = data.content.find(b => b.type === "text");
        if (data.stop_reason === "end_turn" || (textBlock && textBlock.text.includes("{"))) {
          if (textBlock) { finalText = textBlock.text; break; }
        }
        const toolUseBlocks = data.content.filter(b => b.type === "tool_use");
        if (toolUseBlocks.length === 0) {
          if (textBlock) { finalText = textBlock.text; break; }
          throw new Error("No tool use and no text");
        }
        messages.push({
          role: "user",
          content: toolUseBlocks.map(b => ({
            type: "tool_result",
            tool_use_id: b.id,
            content: "Search results received. Continue and return the final JSON."
          }))
        });
      }
      if (!finalText) throw new Error("No final text after tool loop");
      const jsonMatch = finalText.match(/\{[\s\S]*\}/);
      const clean = jsonMatch ? jsonMatch[0] : finalText.replace(/```json|```/g, "").trim();
      setResult(JSON.parse(clean));
    } catch(e) {
      console.error(e);
      alert("Error finding contacts. Try again.");
    }
    setLoading(false);
    setLoadingStage("");
  }

  return (
    <div style={S.page}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 4 }}>Contact Finder</div>
        <div style={{ fontSize: 13, color: "#64748b" }}>AI searches the web for real named contacts and any publicly published email addresses.</div>
      </div>

      <div style={{ display: "flex", gap: 10, marginBottom: 20 }}>
        <input style={{ ...S.input, flex: 1, marginBottom: 0 }} placeholder="Enter company name..." value={company}
          onChange={e => setCompany(e.target.value)}
          onKeyDown={e => e.key === "Enter" && hunt()} />
        <button style={S.btn()} disabled={loading || !company.trim()} onClick={hunt}>
          {loading ? "Searching..." : "Find Contacts"}
        </button>
      </div>

      {loading && (
        <div style={{ ...S.card, textAlign: "center", padding: 30 }}>
          <div style={{ fontSize: 24, marginBottom: 10 }}>🔎</div>
          <div style={{ fontSize: 14, fontWeight: 600, color: "#e8ecf0", marginBottom: 4 }}>{loadingStage}</div>
          <div style={{ fontSize: 12, color: "#64748b" }}>Searching web, LinkedIn, press releases & regulatory filings...</div>
        </div>
      )}

      {/* Quick targets */}
      <div style={{ marginBottom: 20 }}>
        <div style={S.label}>Quick Targets</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {["WaterBridge Infrastructure","Western Midstream Partners","Select Water Solutions","Targa Resources","NGL Energy Partners","Rattler Midstream"].map(c => (
            <button key={c} style={{ ...S.btnOutline, fontSize: 12, padding: "5px 12px" }}
              onClick={() => setCompany(c)}>
              {c}
            </button>
          ))}
        </div>
      </div>

      {result && (
        <div>
          {/* Company header */}
          <div style={{ ...S.card, borderLeft: "3px solid #CC2222" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 8 }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 2 }}>{result.company}</div>
                <div style={{ fontSize: 12, color: "#6366f1", marginBottom: 6 }}>{result.companyType}</div>
              </div>
              {result.domain && (
                <div style={{ background: "#0d0f12", borderRadius: 6, padding: "4px 10px" }}>
                  <div style={{ fontSize: 10, color: "#64748b" }}>Email domain</div>
                  <div style={{ fontSize: 13, color: "#6366f1", fontFamily: "monospace" }}>@{result.domain}</div>
                  {result.emailPattern && <div style={{ fontSize: 10, color: "#475569" }}>pattern: {result.emailPattern}</div>}
                </div>
              )}
            </div>
            <div style={{ fontSize: 13, color: "#94a3b8", lineHeight: 1.5 }}>{result.relevance}</div>
          </div>

          {/* Contact cards */}
          {(result.contacts || []).map((c, i) => (
            <div key={i} style={{ ...S.card, borderLeft: c.priority === "primary" ? "3px solid #CC2222" : "3px solid #1e2330" }}>
              {/* Name / title row */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
                <div>
                  {c.name
                    ? <div style={{ fontSize: 15, fontWeight: 700, color: "#e8ecf0" }}>{c.name}</div>
                    : <div style={{ fontSize: 13, fontStyle: "italic", color: "#475569" }}>Name not found</div>
                  }
                  <div style={{ fontSize: 12, color: "#94a3b8", marginTop: 2 }}>{c.title}</div>
                  <div style={{ ...S.badge(c.priority==="primary"?"#CC2222":"#6b7280"), marginTop: 6 }}>
                    {c.priority === "primary" ? "Primary Target" : "Secondary"}
                  </div>
                </div>
                <div style={{ fontSize: 10, color: "#475569", textAlign: "right" }}>
                  <div style={{ marginBottom: 2 }}>{c.nameSource}</div>
                </div>
              </div>

              <div style={S.divider} />

              {/* Email row */}
              {c.email && (
                <div style={{ background: "#0d0f12", borderRadius: 8, padding: "10px 12px", marginBottom: 10, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                  <div>
                    <div style={{ fontSize: 12, fontFamily: "monospace", color: "#e8ecf0" }}>{c.email}</div>
                    <div style={{ fontSize: 10, color: "#10b981", marginTop: 2 }}>✓ Found publicly published</div>
                    {c.emailSource && <div style={{ fontSize: 10, color: "#475569", marginTop: 1 }}>{c.emailSource}</div>}
                  </div>
                  <button
                    style={{ ...S.btnOutline, fontSize: 11, padding: "4px 10px", whiteSpace: "nowrap", borderColor: copied===`email-${i}` ? "#10b981" : "#1e2330", color: copied===`email-${i}` ? "#10b981" : "#94a3b8" }}
                    onClick={() => copyText(c.email, `email-${i}`)}>
                    {copied===`email-${i}` ? "Copied ✓" : "Copy Email"}
                  </button>
                </div>
              )}

              {/* LinkedIn row */}
              <div style={{ display: "flex", gap: 8, marginBottom: 10, flexWrap: "wrap" }}>
                {c.linkedinUrl && (
                  <a href={c.linkedinUrl} target="_blank" rel="noreferrer"
                    style={{ ...S.btn("#1a6fc4"), fontSize: 11, padding: "6px 12px", textDecoration: "none", display: "inline-block", borderRadius: 8 }}>
                    🔗 View LinkedIn
                  </a>
                )}
                <button
                  style={{ ...S.btnOutline, fontSize: 11, padding: "5px 10px" }}
                  onClick={() => copyText(c.linkedinSearch, `li-${i}`)}>
                  {copied===`li-${i}` ? "Copied ✓" : "Copy LinkedIn Search"}
                </button>
              </div>

              {/* Why + approach */}
              <div style={{ marginBottom: 6 }}>
                <div style={S.label}>Why Target</div>
                <div style={{ fontSize: 13, color: "#94a3b8" }}>{c.why}</div>
              </div>
              <div>
                <div style={S.label}>Outreach Angle</div>
                <div style={{ fontSize: 13, color: "#94a3b8" }}>{c.approach}</div>
              </div>
            </div>
          ))}

          {/* Email disclaimer */}
          <div style={{ fontSize: 11, color: "#334155", textAlign: "center", padding: "8px 0 20px" }}>
            Emails shown are sourced from publicly indexed web content. LinkedIn is your best path for contacts without a listed email.
          </div>
        </div>
      )}
    </div>
  );
}


// ─── ASSETS TAB ──────────────────────────────────────────────────
function AssetsTab() {
  const [company, setCompany] = React.useState("");
  const [report, setReport] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [loadingStage, setLoadingStage] = React.useState("");
  const [savedReports, setSavedReports] = React.useState([]);
  const [viewingSaved, setViewingSaved] = React.useState(false);

  React.useEffect(() => {
    DB.loadAssetReports().then(setSavedReports);
  }, []);

  async function runDeepDive() {
    if (!company.trim()) return;
    setLoading(true);
    setReport(null);
    setViewingSaved(false);

    const system = `You are a pipeline asset intelligence analyst for Internal Pipeline Services (IPS), a pipeline cleaning and epoxy lining contractor targeting produced water, brine, and SWD pipelines.

CRITICAL FILTER: Only include pipeline assets that carry produced water, brine, saltwater, or SWD (saltwater disposal). Completely ignore and exclude gas transmission, natural gas gathering, crude oil, refined products, NGL, and any other non-water service pipelines. If a company has no produced water, brine, or SWD assets, say so in the overview and return empty systems array.

Return a JSON object for the target company with these fields — be concise, max 2 sentences per text field:
- "company": company name
- "overview": 2-sentence summary of their produced water / brine / SWD pipeline footprint specifically
- "totalMileage": total mileage of produced water/brine/SWD assets only (e.g. "~850 miles" or "unknown")
- "ipsOpportunityScore": "high" | "medium" | "low"
- "ipsOpportunityReason": 1-sentence reason based only on water/brine/SWD assets
- "systems": array of up to 6 known produced water / brine / SWD pipeline systems only, each: { "name", "length", "diameter", "service", "installYear", "age", "region", "condition", "ipsRelevance" } — use "unknown" for missing fields
- "incidents": array of up to 3 known PHMSA incidents on water/brine lines: { "date", "description", "cause", "source" } — empty array if none known
- "iliData": 1-2 sentences on any known ILI or integrity data for water/brine lines, or "No ILI data found publicly"
- "recentActivity": array of up to 4 brief recent developments on produced water / brine / SWD infrastructure
- "dataQuality": "high" | "medium" | "low"
- "dataSources": array of up to 5 source names (no full URLs needed)
- "lastUpdated": today as ISO date string

Return ONLY valid JSON. No markdown, no explanation.`;

    const stages = [
      "Searching PHMSA incident database...",
      "Pulling RRC permit filings...",
      "Scanning press releases & earnings calls...",
      "Analyzing pipeline asset data...",
      "Building intelligence report..."
    ];
    let stageIdx = 0;
    setLoadingStage(stages[0]);
    const stageTimer = setInterval(() => {
      stageIdx = Math.min(stageIdx + 1, stages.length - 1);
      setLoadingStage(stages[stageIdx]);
    }, 8000);

    try {
      const res = await fetch(PROXY_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          model: "claude-sonnet-4-6",
          max_tokens: 2500,
          system,
          messages: [{ role: "user", content: `Run a produced water / brine / SWD pipeline asset deep dive on: "${company}". Today's date: ${new Date().toLocaleDateString()}. Focus ONLY on produced water, brine, and saltwater disposal assets — ignore all gas, crude, NGL, and refined product lines. Draw on PHMSA records, SEC/investor filings, earnings calls, press releases, RRC data, and trade publications. Be specific — real system names, real mileage, real diameters. Use "unknown" for missing fields. Return ONLY the JSON object, nothing else.` }]
        })
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      const data = await res.json();
      if (data.error) throw new Error(data.error.message || JSON.stringify(data.error));
      const textBlock = (data.content || []).find(b => b.type === "text");
      if (!textBlock) throw new Error("No text in response: " + JSON.stringify(data).slice(0,200));
      const raw = textBlock.text.trim();
      const jsonMatch = raw.match(/\{[\s\S]*\}/);
      const clean = jsonMatch ? jsonMatch[0] : raw.replace(/```json|```/g, "").trim();
      const parsed = JSON.parse(clean);
      setReport(parsed);
      await DB.saveAssetReport(parsed);
      setSavedReports(prev => {
        const key = parsed.company.replace(/[^a-zA-Z0-9]/g,"_").toLowerCase();
        const filtered = prev.filter(r => r.id !== key);
        return [{ id: key, ...parsed, createdAt: Date.now() }, ...filtered];
      });
    } catch(e) {
      console.error("Asset deep dive error:", e);
      alert("Error: " + e.message);
    }
    clearInterval(stageTimer);
    setLoading(false);
    setLoadingStage("");
  }

  function openSaved(r) {
    setReport(r);
    setViewingSaved(true);
    setCompany(r.company);
  }

  async function deleteSaved(id, e) {
    e.stopPropagation();
    if (!confirm("Delete this report?")) return;
    await DB.deleteAssetReport(id);
    setSavedReports(prev => prev.filter(r => r.id !== id));
    if (viewingSaved && report && report.company && report.company.replace(/[^a-zA-Z0-9]/g,"_").toLowerCase() === id) {
      setReport(null); setViewingSaved(false);
    }
  }

  const qualityColor = { high: "#10b981", medium: "#f59e0b", low: "#6b7280" };
  const oppColor = { high: "#CC2222", medium: "#f97316", low: "#6b7280" };

  return (
    <div style={S.page}>
      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 4 }}>Asset Intelligence</div>
        <div style={{ fontSize: 13, color: "#64748b" }}>AI deep dive on a company's pipeline infrastructure — mileage, diameters, age, service type, ILI data, and PHMSA incidents.</div>
      </div>

      <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
        <input style={{ ...S.input, flex: 1, marginBottom: 0 }}
          placeholder="Enter company name..."
          value={company}
          onChange={e => setCompany(e.target.value)}
          onKeyDown={e => e.key === "Enter" && runDeepDive()} />
        <button style={S.btn()} disabled={loading || !company.trim()} onClick={runDeepDive}>
          {loading ? "Researching..." : "Deep Dive"}
        </button>
      </div>

      <div style={{ marginBottom: 20 }}>
        <div style={S.label}>Quick Targets</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {["WaterBridge Infrastructure","Western Midstream Partners","Select Water Solutions","Targa Resources","NGL Energy Partners","Crestwood Midstream"].map(c => (
            <button key={c} style={{ ...S.btnOutline, fontSize: 12, padding: "5px 12px" }}
              onClick={() => setCompany(c)}>{c}</button>
          ))}
        </div>
      </div>

      {savedReports.length > 0 && !loading && !report && (
        <div style={{ marginBottom: 20 }}>
          <div style={S.label}>Saved Reports ({savedReports.length})</div>
          {savedReports.map(r => (
            <div key={r.id} style={{ ...S.card, cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" }}
              onClick={() => openSaved(r)}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700 }}>{r.company}</div>
                <div style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}>
                  {r.totalMileage} · <span style={{ color: oppColor[r.ipsOpportunityScore] || "#6b7280" }}>
                    {r.ipsOpportunityScore ? r.ipsOpportunityScore.toUpperCase() : ""} opportunity
                  </span>
                </div>
                {r.createdAt && <div style={{ fontSize: 10, color: "#334155", marginTop: 2 }}>{new Date(r.createdAt).toLocaleDateString()}</div>}
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <button style={{ ...S.btn("#1a1e26"), border: "1px solid #1e2330", fontSize: 11, padding: "4px 10px" }} onClick={() => openSaved(r)}>View</button>
                <button style={{ ...S.btnOutline, fontSize: 11, padding: "4px 10px", color: "#CC2222" }} onClick={e => deleteSaved(r.id, e)}>✕</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {loading && (
        <div style={{ ...S.card, textAlign: "center", padding: 40 }}>
          <div style={{ fontSize: 28, marginBottom: 12 }}>🛰️</div>
          <div style={{ fontSize: 15, fontWeight: 700, color: "#e8ecf0", marginBottom: 6 }}>{loadingStage}</div>
          <div style={{ fontSize: 12, color: "#64748b" }}>Searching PHMSA, RRC, SEC filings, press releases...</div>
          <div style={{ fontSize: 11, color: "#334155", marginTop: 8 }}>This may take 30–60 seconds</div>
        </div>
      )}

      {report && !loading && (
        <div>
          <div style={{ ...S.card, borderLeft: "3px solid #CC2222" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 8, marginBottom: 10 }}>
              <div>
                <div style={{ fontSize: 18, fontWeight: 800 }}>{report.company}</div>
                <div style={{ fontSize: 12, color: "#64748b", marginTop: 2 }}>Total pipeline: <span style={{ color: "#e8ecf0", fontWeight: 700 }}>{report.totalMileage}</span></div>
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {report.ipsOpportunityScore && <div style={{ ...S.badge(oppColor[report.ipsOpportunityScore] || "#6b7280"), fontSize: 12 }}>{report.ipsOpportunityScore.toUpperCase()} OPPORTUNITY</div>}
                {report.dataQuality && <div style={{ ...S.badge(qualityColor[report.dataQuality] || "#6b7280"), fontSize: 11 }}>{report.dataQuality.toUpperCase()} DATA QUALITY</div>}
              </div>
            </div>
            <div style={{ fontSize: 13, color: "#94a3b8", lineHeight: 1.6, marginBottom: 8 }}>{report.overview}</div>
            {report.ipsOpportunityReason && (
              <div style={{ background: "#0d0f12", borderRadius: 6, padding: "8px 12px", fontSize: 12, color: "#10b981" }}>
                💡 {report.ipsOpportunityReason}
              </div>
            )}
          </div>

          {(report.systems || []).length > 0 && (
            <div style={S.card}>
              <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12 }}>📍 Pipeline Systems & Assets</div>
              {(report.systems || []).map((sys, i) => (
                <div key={i} style={{ borderTop: i === 0 ? "none" : "1px solid #1e2330", paddingTop: i === 0 ? 0 : 12, marginTop: i === 0 ? 0 : 12 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 6, marginBottom: 6 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "#e8ecf0" }}>{sys.name}</div>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                      {sys.service && sys.service !== "unknown" && <span style={{ ...S.badge("#6366f1"), fontSize: 10 }}>{sys.service}</span>}
                      {sys.age && sys.age !== "unknown" && <span style={{ ...S.badge("#f59e0b"), fontSize: 10 }}>{sys.age}</span>}
                    </div>
                  </div>
                  <div style={{ display: "flex", gap: 16, flexWrap: "wrap", marginBottom: 6 }}>
                    {[["Length", sys.length],["Diameter", sys.diameter],["Region", sys.region],["Installed", sys.installYear]].filter(([,v]) => v && v !== "unknown").map(([k,v]) => (
                      <div key={k}>
                        <div style={{ fontSize: 10, color: "#64748b" }}>{k}</div>
                        <div style={{ fontSize: 12, color: "#e8ecf0", fontWeight: 600 }}>{v}</div>
                      </div>
                    ))}
                  </div>
                  {sys.condition && sys.condition !== "no data found" && (
                    <div style={{ background: "#0d0f12", borderRadius: 6, padding: "6px 10px", fontSize: 11, color: "#f59e0b", marginBottom: 4 }}>⚠️ {sys.condition}</div>
                  )}
                  {sys.ipsRelevance && <div style={{ fontSize: 11, color: "#64748b", fontStyle: "italic" }}>→ {sys.ipsRelevance}</div>}
                </div>
              ))}
            </div>
          )}

          {(report.incidents || []).length > 0 && (
            <div style={S.card}>
              <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12, color: "#CC2222" }}>🚨 PHMSA Incidents / Failures</div>
              {(report.incidents || []).map((inc, i) => (
                <div key={i} style={{ borderTop: i === 0 ? "none" : "1px solid #1e2330", paddingTop: i === 0 ? 0 : 10, marginTop: i === 0 ? 0 : 10 }}>
                  <div style={{ fontSize: 11, color: "#CC2222", fontWeight: 700, marginBottom: 4 }}>{inc.date}</div>
                  <div style={{ fontSize: 13, color: "#e8ecf0", marginBottom: 2 }}>{inc.description}</div>
                  {inc.cause && <div style={{ fontSize: 11, color: "#64748b" }}>Cause: {inc.cause}</div>}
                  {inc.source && <div style={{ fontSize: 10, color: "#334155", marginTop: 2 }}>{inc.source}</div>}
                </div>
              ))}
            </div>
          )}

          <div style={S.card}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 8 }}>🔬 ILI / Integrity Data</div>
            <div style={{ fontSize: 13, color: "#94a3b8", lineHeight: 1.6 }}>{report.iliData}</div>
          </div>

          {(report.recentActivity || []).length > 0 && (
            <div style={S.card}>
              <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10 }}>⚡ Recent Activity</div>
              {(report.recentActivity || []).map((item, i) => (
                <div key={i} style={{ display: "flex", gap: 10, marginBottom: 8, alignItems: "flex-start" }}>
                  <div style={{ color: "#CC2222", fontWeight: 700, minWidth: 16 }}>›</div>
                  <div style={{ fontSize: 13, color: "#cbd5e1", lineHeight: 1.5 }}>{item}</div>
                </div>
              ))}
            </div>
          )}

          {(report.dataSources || []).length > 0 && (
            <div style={{ ...S.card, marginBottom: 8 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: "#64748b", marginBottom: 8 }}>Sources</div>
              {(report.dataSources || []).map((src, i) => (
                <div key={i} style={{ fontSize: 11, color: "#334155", marginBottom: 3, wordBreak: "break-all" }}>{src}</div>
              ))}
            </div>
          )}

          <button style={{ ...S.btnOutline, width: "100%", marginBottom: 24 }} onClick={() => { setReport(null); setViewingSaved(false); }}>
            ← Back to Reports
          </button>
        </div>
      )}
    </div>
  );
}

// ─── APP SHELL ───────────────────────────────────────────────────
function App() {
  const [unlocked, setUnlocked] = React.useState(false);
  const [tab, setTab] = React.useState("hunt");
  const [pendingPipelineLead, setPendingPipelineLead] = React.useState(null);
  const [pendingOutreachLead, setPendingOutreachLead] = React.useState(null);

  React.useEffect(() => {
    initFirebase();
  }, []);

  function handleAddToPipeline(lead) {
    setPendingPipelineLead(lead);
    setTab("pipeline");
  }

  function handleGenerateOutreach(prospect) {
    setPendingOutreachLead(prospect);
    setTab("outreach");
  }

  if (!unlocked) return <PinScreen onUnlock={() => setUnlocked(true)} />;

  const TABS = [
    { key: "hunt",     label: "🔍 Hunt" },
    { key: "contacts", label: "👤 Contacts" },
    { key: "outreach", label: "✉️ Outreach" },
    { key: "pipeline", label: "📋 Pipeline" },
    { key: "assets",   label: "🛰️ Assets" },
  ];

  return (
    <div style={S.app}>
      {/* Header */}
      <div style={S.header}>
        <div>
          <div style={S.headerTitle}>IPSProspect</div>
          <div style={S.headerSub}>Internal Pipeline Services · BD Intelligence</div>
        </div>
      </div>

      {/* Tabs */}
      <div style={S.tabs}>
        {TABS.map(t => (
          <button key={t.key} style={S.tab(tab===t.key)} onClick={() => setTab(t.key)}>{t.label}</button>
        ))}
      </div>

      {/* Pages */}
      {tab === "hunt"     && <HuntTab onAddToPipeline={handleAddToPipeline} />}
      {tab === "contacts" && <ContactsTab />}
      {tab === "outreach" && <OutreachTab pendingLead={pendingOutreachLead} onClearPending={() => setPendingOutreachLead(null)} />}
      {tab === "pipeline" && <PipelineTab newProspect={pendingPipelineLead} onClearNew={() => setPendingPipelineLead(null)} onGenerateOutreach={handleGenerateOutreach} />}
      {tab === "assets"   && <AssetsTab />}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
