// ============================================================
// LynkedUp Pro — Pipeline (kanban) mock data.
// Mirrors the /owner/kanban board: seven progression stages
// (New Lead → Complete) plus two flag columns (Stuck,
// Follow-Up). Each lead carries the fields the detail drawer
// needs (contact, job, assignment, notes, timeline) and its
// activity trail is generated from the stage it has reached.
// All client-side so the board is fully interactive.
// ============================================================

export type StageKey =
  | "new" | "contacted" | "appt" | "estimate" | "signed" | "progress" | "complete"
  | "stuck" | "followup";

export type Stage = { key: StageKey; label: string; tone: string; flag?: boolean };

export const STAGES: Stage[] = [
  { key: "new",       label: "New Lead",       tone: "blue" },
  { key: "contacted", label: "Contacted",      tone: "purple" },
  { key: "appt",      label: "Appt Scheduled", tone: "magenta" },
  { key: "estimate",  label: "Estimate Sent",  tone: "orange" },
  { key: "signed",    label: "Signed",         tone: "green" },
  { key: "progress",  label: "In Progress",    tone: "cyan" },
  { key: "complete",  label: "Complete",       tone: "green" },
  { key: "stuck",     label: "Stuck",          tone: "red",    flag: true },
  { key: "followup",  label: "Follow-Up",      tone: "orange", flag: true },
];

// The linear progression — these are the "7 stages" shown in the header.
export const PROGRESSION: StageKey[] = ["new", "contacted", "appt", "estimate", "signed", "progress", "complete"];

const STAGE_LABEL: Record<StageKey, string> = Object.fromEntries(STAGES.map((s) => [s.key, s.label])) as Record<StageKey, string>;

/** Percent-complete for the drawer progress bar (0–100), based on furthest progression reached. */
export function pctFor(reached: StageKey): number {
  const i = PROGRESSION.indexOf(reached);
  if (i < 0) return 0;
  return Math.round(((i + 1) / PROGRESSION.length) * 100);
}

export type Phone = { number: string; type: string; primary?: boolean };

export type Insurance = {
  company: string; claimStatus: string; claimNumber: string;
  policyNumber: string; adjusterName: string; adjusterPhone: string;
};

export type Assignment = {
  assignedTo: string; priority: string; followUp: string;
  createdBy: string; createdAt: string;
};

export type PLead = {
  id: string;
  initials: string;
  name: string;
  gradient: string;
  stage: StageKey;      // which column it currently sits in
  reached: StageKey;    // furthest progression stage reached (== stage for progression columns)
  address: string;
  city: string;
  state: string;
  zip: string;
  workType: string;     // "Roof Replacement"
  leadType: string;     // "Insurance" | "Retail"
  rep: string;          // "Cody Tatum" | "Unassigned"
  storm: boolean;
  ageDays: number;      // days in pipeline → shown as "59d"
  phone: string;
  email: string;
  notes: string;
  createdAt: string;    // "Feb 10, 2026"

  // --- detail page only (the board + drawer ignore these) ---
  propertyType: string; // "Single Family"
  phones: Phone[];      // primary mobile + a secondary line
  source: string;       // "Door Knock"
  tradeType: string;    // derived from workType
  urgency: string;      // "Standard" | "High" | "Emergency"
  insurance: Insurance | null; // null for Retail jobs — no claim to track
  assignment: Assignment;
};

export type Activity = { from?: string; to: string; by: string; date: string; note: string };

const G = [
  "linear-gradient(135deg,#fda913,#fd6d13)",
  "linear-gradient(135deg,#4f8cff,#2c5cff)",
  "linear-gradient(135deg,#b07bf2,#7b53e0)",
  "linear-gradient(135deg,#33c98a,#1fa46c)",
  "linear-gradient(135deg,#34c9d6,#1f9aa4)",
  "linear-gradient(135deg,#f0563f,#c9372a)",
  "linear-gradient(135deg,#d452c8,#a02f97)",
];

const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// Fixed reference "today" — deterministic (no Date.now) so server and client render identically.
const BASE = Date.UTC(2026, 6, 24);
const DAY = 86_400_000;

function fmt(ts: number): string {
  const d = new Date(ts);
  return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
}
function initialsOf(name: string): string {
  return name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase();
}
function emailOf(name: string): string {
  const [first, last] = name.toLowerCase().split(/\s+/);
  return `${first[0]}${last}@gmail.com`;
}
const AREA = ["972", "469", "214"];
function phoneOf(i: number): string {
  const area = AREA[i % AREA.length];
  const mid = 200 + ((i * 37) % 700);
  const end = 1000 + ((i * 53) % 8999);
  return `(${area}) ${mid}-${end}`;
}

// Terse rows keep the file readable; full records are expanded below.
// [ name, stage, reached, address, workType, leadType, rep, storm, ageDays ]
type Row = [string, StageKey, StageKey, string, string, string, string, boolean, number];

const ROWS: Row[] = [
  // New Lead
  ["Derek Holloway",  "new", "new", "2814 Ravenswood Dr",   "Roof Replacement", "Insurance", "Cody Tatum",   true,  59],
  ["Brenda Castillo", "new", "new", "5501 Shady Brook Ln",  "Roof Inspection",  "Retail",    "Unassigned",   false, 58],
  ["Antonio Reyes",   "new", "new", "1122 Custer Rd",       "Gutter Repair",    "Retail",    "Hannah Reyes", false, 57],
  ["Sylvia Nguyen",   "new", "new", "3308 Roundrock Trl",   "Siding Repair",    "Insurance", "Shelby Greer", true,  56],
  ["Raymond Osei",    "new", "new", "4720 Preston Rd",      "Roof Replacement", "Insurance", "Unassigned",   false, 55],
  ["Carolyn Estrada", "new", "new", "6013 Ohio Dr",         "Window Replacement","Retail",   "Dalton Pruitt",false, 54],
  // Contacted
  ["Marcus Tillman",  "contacted", "contacted", "2201 Willow Bend Dr",   "Roof Replacement", "Insurance", "Cody Tatum",   true,  65],
  ["Diane Kowalski",  "contacted", "contacted", "815 Independence Pkwy", "Roof Inspection",  "Retail",    "Hannah Reyes", false, 64],
  ["Joel Fernandez",  "contacted", "contacted", "3901 Legacy Dr",        "Siding Replacement","Insurance","Shelby Greer", true,  66],
  ["Patricia Yuen",   "contacted", "contacted", "7742 Kings Rd",         "Gutter Repair",    "Retail",    "Travis Boone", false, 63],
  ["Gerald Obi",      "contacted", "contacted", "5220 Midway Rd",        "Roof Replacement", "Insurance", "Cody Tatum",   true,  68],
  // Appt Scheduled
  ["Vanessa Obrien",  "appt", "appt", "1450 Park Blvd",       "Roof Replacement", "Insurance", "Shelby Greer", true,  72],
  ["Thomas Greer",    "appt", "appt", "892 Mapleshade Ln",    "Roof Inspection",  "Retail",    "Hannah Reyes", false, 70],
  ["Lashonda Webb",   "appt", "appt", "3015 Plano Pkwy",      "Siding + Gutters", "Insurance", "Cody Tatum",   true,  75],
  ["Winston Park",    "appt", "appt", "6601 Ohio Dr",         "Roof Replacement", "Insurance", "Dalton Pruitt",true,  71],
  ["Ingrid Solis",    "appt", "appt", "2244 Aster Ct",        "Roof Replacement", "Retail",    "Shelby Greer", false, 67],
  ["Darnell Brooks",  "appt", "appt", "4406 Springbrook Dr",  "Chimney + Roof Repair","Insurance","Hannah Reyes",false, 80],
  // Estimate Sent
  ["Gloria Hutchins", "estimate", "estimate", "1738 Roundrock Trl", "Roof Replacement", "Insurance", "Cody Tatum",   true,  85],
  ["Devon Mathis",    "estimate", "estimate", "5902 Braewood Dr",   "Siding Replacement","Insurance","Shelby Greer", true,  82],
  ["Karen Blankenship","estimate","estimate", "3127 Arbor Creek Dr","Roof Replacement", "Retail",    "Hannah Reyes", false, 78],
  ["Lionel Chambers", "estimate", "estimate", "720 Coit Rd",        "Gutters + Fascia", "Insurance", "Dalton Pruitt",false, 89],
  ["Ruthanne Patel",  "estimate", "estimate", "4321 Hedgcoxe Rd",   "Roof Replacement", "Insurance", "Cody Tatum",   false, 98],
  // Signed
  ["Charlotte Norris","signed", "signed", "2908 Roundabout Ln",  "Roof Replacement", "Insurance", "Shelby Greer", true,  89],
  ["Henry Castaneda", "signed", "signed", "5614 Ridgewood Dr",   "Siding Replacement","Insurance","Hannah Reyes", false, 90],
  ["Yvonne Blackwell","signed", "signed", "3401 Parker Rd",      "Roof Replacement", "Retail",    "Cody Tatum",   false, 85],
  ["Emmanuel Okafor", "signed", "signed", "4812 Mapleshade Ln",  "Roof + Gutters",   "Insurance", "Dalton Pruitt",true,  87],
  ["Adriana Voss",    "signed", "signed", "1820 Custer Rd",      "Roof Replacement", "Insurance", "Shelby Greer", true,  103],
  // In Progress
  ["Marvin Delgado",  "progress", "progress", "6820 Windhaven Pkwy", "Roof Replacement", "Insurance", "Cody Tatum",   true,  108],
  ["Sandra Tran",     "progress", "progress", "2506 Springpark Dr",  "Siding Replacement","Insurance","Hannah Reyes", false, 110],
  ["Reginald Hopper", "progress", "progress", "1504 Estates Dr",     "Roof + Gutters",   "Insurance", "Shelby Greer", false, 113],
  ["Nadia Thornton",  "progress", "progress", "5150 Preston Rd",     "Roof Replacement", "Retail",    "Dalton Pruitt",false, 106],
  ["Clifford Aguilar","progress", "progress", "3622 Haverwood Ln",   "Siding Repair",    "Insurance", "Cody Tatum",   true,  100],
  ["Tamara Owens",    "progress", "progress", "2010 Oak Creek Blvd", "Roof Replacement", "Insurance", "Hannah Reyes", true,  117],
  // Complete
  ["Craig Singleton", "complete", "complete", "4110 Lorimar Dr",     "Roof Replacement", "Insurance", "Cody Tatum",   false, 134],
  ["Bertha Fleming",  "complete", "complete", "6230 West Parker Rd", "Siding Replacement","Insurance","Shelby Greer", false, 139],
  ["Oliver Stanton",  "complete", "complete", "3750 Legacy Dr",      "Roof Replacement", "Retail",    "Hannah Reyes", false, 129],
  ["Daphne Garrett",  "complete", "complete", "1912 Mira Vista Dr",  "Gutters + Fascia", "Insurance", "Dalton Pruitt",false, 124],
  ["Nathaniel Cruz",  "complete", "complete", "5808 Tennyson Pkwy",  "Roof Replacement", "Insurance", "Shelby Greer", true,  144],
  // Stuck (flag) — reached shows where they stalled
  ["Jasmine Fowler",  "stuck", "estimate", "2730 Hedgcoxe Rd",     "Roof Replacement", "Insurance", "Travis Boone", false, 93],
  ["Calvin Merritt",  "stuck", "appt",     "3640 Alma Dr",         "Siding Replacement","Insurance","Hannah Reyes", false, 80],
  ["Harriet Simmons", "stuck", "contacted","4905 Ohio Dr",         "Roof Replacement", "Retail",    "Dalton Pruitt",false, 85],
  // Follow-Up (flag)
  ["Floyd Saunders",  "followup", "contacted","1344 Spring Creek Pkwy","Roof Replacement","Insurance","Cody Tatum",  true,  75],
  ["Miriam Obando",   "followup", "new",      "2217 Independence Pkwy","Roof Inspection", "Retail",   "Shelby Greer", false, 70],
  ["Jerome Watkins",  "followup", "contacted","3908 Plano Pkwy",       "Gutter Replacement","Insurance","Travis Boone",false, 82],
];

// Per-lead note overrides keyed by name (the rest fall back to a stage template).
const NOTE_OVERRIDE: Record<string, string> = {
  "Marvin Delgado": "Tear-off complete. New decking going on today.",
  "Derek Holloway": "Homeowner reported hail damage after the April storm; door-knocked.",
  "Jasmine Fowler": "Estimate sent but homeowner has gone quiet — three follow-ups, no reply.",
  "Floyd Saunders": "Wants to wait until his insurance adjuster visits next week.",
};

function noteFor(reached: StageKey, storm: boolean): string {
  switch (reached) {
    case "new":       return storm ? "Storm canvassing — fresh lead." : "Inbound lead — needs first contact.";
    case "contacted": return "Spoke with homeowner; interest confirmed.";
    case "appt":      return "Inspection appointment scheduled.";
    case "estimate":  return "Estimate delivered; awaiting decision.";
    case "signed":    return "Contract signed; production queued.";
    case "progress":  return "Crew on site — job underway.";
    case "complete":  return "Job complete. Final invoice cleared.";
    default:          return "";
  }
}

export const LEADS: PLead[] = ROWS.map(([name, stage, reached, address, workType, leadType, rep, storm, ageDays], i) => ({
  id: `SAL-${(101 + i).toString()}`,
  initials: initialsOf(name),
  name,
  gradient: G[i % G.length],
  stage,
  reached,
  address,
  city: "Plano",
  state: "TX",
  zip: "750" + (21 + (i % 5)).toString().padStart(2, "0"),
  workType,
  leadType,
  rep,
  storm,
  ageDays,
  phone: phoneOf(i),
  email: emailOf(name),
  notes: NOTE_OVERRIDE[name] ?? noteFor(reached, storm),
  createdAt: fmt(BASE - ageDays * DAY),
}));

/** Build the drawer Activity trail from the stage a lead has reached. */
export function buildActivity(lead: PLead): Activity[] {
  const by = lead.rep === "Unassigned" ? "System" : lead.rep;
  const items: Activity[] = [];
  const created = BASE - lead.ageDays * DAY;
  items.push({ to: "Lead Created", by, date: fmt(created), note: lead.storm ? "Storm canvassing." : "Inbound lead." });

  const reachedIdx = PROGRESSION.indexOf(lead.reached);
  const stepNotes: Record<StageKey, string> = {
    new: "", contacted: "Call completed.", appt: "Inspection scheduled.",
    estimate: "Estimate sent.", signed: "Signed. Production team notified.",
    progress: "Production started — crew on site.", complete: "Job complete. Final invoice cleared.",
    stuck: "", followup: "",
  };
  const steps = Math.max(reachedIdx, 0);
  for (let i = 0; i < steps; i++) {
    const from = PROGRESSION[i];
    const to = PROGRESSION[i + 1];
    const when = created + Math.round(((i + 1) / (steps + 1)) * lead.ageDays) * DAY;
    items.push({ from: STAGE_LABEL[from], to: STAGE_LABEL[to], by, date: fmt(when), note: stepNotes[to] });
  }

  if (lead.stage === "stuck") {
    items.push({ from: STAGE_LABEL[lead.reached], to: "Stuck", by: "System", date: fmt(BASE - 3 * DAY), note: "Flagged — no response from homeowner." });
  } else if (lead.stage === "followup") {
    items.push({ from: STAGE_LABEL[lead.reached], to: "Follow-Up", by, date: fmt(BASE - 2 * DAY), note: "Moved to follow-up queue." });
  }
  return items;
}

// Header stat — the loaded board is a slice of the full book.
export const TOTAL_LEADS = LEADS.length;
