// Shared utilities for both directions
// ─────────────────────────────────────────────────────────────

const RELAY_RULES = {
  spam: [
    "crypto", "airdrop", "dm us", "dm me", "forex", "giveaway", "promo",
    "promote", "check my page", "check my profile", "followers", "investment",
    "bitcoin", "free money", "link in bio", "click the link",
  ],
  negative: [
    "mid", "flat", "boring", "bad", "trash", "hate", "awful", "weak",
    "overrated", "ugly", "lame", "terrible", "washed", "cringe", "tbh",
  ],
  question: [
    "where", "what", "when", "why", "how", "which", "camera", "lens",
    "price", "cost", "sale", "available", "setup", "location", "spec",
    "settings", "buy",
  ],
  positive: [
    "love", "insane", "fire", "clean", "crazy", "beautiful", "sick",
    "hard", "amazing", "legend", "elite", "perfect", "wow", "need this",
  ],
};

function normalizeRelayText(comment) {
  return String(comment || "").trim().toLowerCase();
}

function usesEmoji(comment) {
  return /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(comment || "");
}

function includesAny(text, needles) {
  return needles.some((needle) => text.includes(needle));
}

function inferBucket(text) {
  if (!text) return "Fan";
  if (includesAny(text, RELAY_RULES.spam)) return "Spam";
  if (includesAny(text, RELAY_RULES.negative)) return "Negative";
  if (text.includes("?") || includesAny(text, RELAY_RULES.question)) return "Question";
  return "Fan";
}

function inferSentiment(text, bucket) {
  if (bucket === "Negative") return "Negative";
  if (bucket === "Spam") return "Neutral";
  if (includesAny(text, RELAY_RULES.positive) || /[!]{1,}/.test(text) || usesEmoji(text)) {
    return "Positive";
  }
  if (bucket === "Question") return "Neutral";
  return "Positive";
}

function buildReply(text, bucket) {
  const emoji = usesEmoji(text);

  if (bucket === "Spam") return "filtering this one out.";

  if (bucket === "Negative") {
    if (text.includes("flat")) return "fair read, i was chasing a softer frame on this set.";
    if (text.includes("mid")) return "not every frame needs to swing for the fences, but i hear you.";
    return "fair note, i am always tuning the edit.";
  }

  if (bucket === "Question") {
    if (text.includes("where") || text.includes("location")) return "shot this in seoul, more from that run soon.";
    if (text.includes("camera") || text.includes("lens") || text.includes("settings")) {
      return "sony body, 50mm glass, low light, and a lot of patience.";
    }
    if (text.includes("sale") || text.includes("available") || text.includes("buy") || text.includes("price") || text.includes("cost")) {
      return "not for sale, but happy to share the spec if that helps.";
    }
    return "good question, i will break that down in the next post.";
  }

  if (text.includes("992")) return "appreciate it, that 992 set was a fun one to chase.";
  if (text.includes("love")) return emoji ? "appreciate it 🔥" : "appreciate it, more soon.";
  if (text.includes("insane") || text.includes("crazy") || text.includes("fire")) return "glad it landed, this one was worth waiting for.";
  return emoji ? "appreciate it 🙏" : "appreciate it.";
}

function heuristicRelayResponse(comment) {
  const text = normalizeRelayText(comment);
  const bucket = inferBucket(text);
  return {
    bucket,
    sentiment: inferSentiment(text, bucket),
    reply: buildReply(text, bucket),
    _engine: "heuristic",
  };
}

async function classifyAndReply(comment, persona = "Maxwell - automotive photographer, dry humor, west-coast laid-back") {
  const fallback = heuristicRelayResponse(comment);
  const claude = window.claude?.complete;

  if (!claude) return fallback;

  const prompt = `You are Relay, an AI that helps an Instagram creator triage and reply to comments.

Persona of the creator: ${persona}

Incoming comment: "${comment}"

Respond ONLY with a compact JSON object - no prose, no code fences:
{
  "bucket": one of "Question" | "Fan" | "Negative" | "Spam",
  "sentiment": one of "Positive" | "Neutral" | "Negative",
  "reply": a short reply in the creator's voice - 1 sentence, lowercase ok, no hashtags, no emojis unless the original comment used them
}`;

  try {
    const raw = await Promise.race([
      claude(prompt),
      new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 1800)),
    ]);
    const m = raw.match(/\{[\s\S]*\}/);
    if (!m) throw new Error("no json");
    const parsed = JSON.parse(m[0]);
    if (!parsed.bucket || !parsed.sentiment || !parsed.reply) throw new Error("bad payload");
    return { ...parsed, _engine: "claude" };
  } catch (e) {
    return fallback;
  }
}

// Tiny pre-canned dataset used to seed demos before user types
const SEED_COMMENTS = [
  { user: "fan123", text: "love the 992 shots!" },
  { user: "maxwellgrove", text: "this shot is insane 🔥 where is this??" },
  { user: "carbuyer.la", text: "is this car for sale" },
  { user: "negativenick", text: "lighting looks flat tbh" },
  { user: "spambot_007", text: "🚀🚀 check my page for crypto airdrops 🚀🚀" },
];

// Rotating dataset hook for ambient demo
function useRotating(items, ms = 2400) {
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setI(x => (x + 1) % items.length), ms);
    return () => clearInterval(t);
  }, [items, ms]);
  return [items[i], i];
}

// Small inline icon set — kept abstract, no slop
const Icon = {
  arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}>
      <path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  dot: (p) => (
    <svg viewBox="0 0 8 8" {...p}><circle cx="4" cy="4" r="3" fill="currentColor"/></svg>
  ),
  spark: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}>
      <path d="M12 3v6M12 15v6M3 12h6M15 12h6M5.6 5.6l4.2 4.2M14.2 14.2l4.2 4.2M5.6 18.4l4.2-4.2M14.2 9.8l4.2-4.2" strokeLinecap="round"/>
    </svg>
  ),
  check: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M5 12l5 5 9-12" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  plus: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}>
      <path d="M12 5v14M5 12h14" strokeLinecap="round"/>
    </svg>
  ),
};

Object.assign(window, { classifyAndReply, SEED_COMMENTS, useRotating, Icon });
