/**
 * Industry presets. A workspace's industry (`settings.industry`) shapes the whole internal module for that category:
 * pipeline/funnel stages, lead fields, the AI agent's role, questions and compliance guardrails, terminology,
 * the name of the booked step, knowledge-base starters, saved replies, SLA and AI defaults, and examples.
 *
 * Stable internal keys keep the API contract and ad-platform mappings unchanged: stage ids `new`, `qualified`,
 * `site_visit` (the booked step, conversion event `SiteVisit`), `won`, `lost`; activity type `visit`; metric `site_visits`.
 */
import type { PipelineStage, WorkspaceSettings } from "@/db/schema";

export type QualField = { key: string; label: string; ask: string };
export type FieldDef = { key: string; label: string; type: "text" | "number" | "date" | "dropdown" | "multiselect"; options?: string[] };
export type IndustryPreset = {
  key: string;
  group: "service" | "product" | "other";
  label: string;
  examples: string; // what the category covers (shown in pickers)
  business: string; // AI prompt: "<workspace>, a …"
  offering: string; // what is sold
  projectLabel: string; // label for contact.project ("Project", "Product", "Service"…)
  visit: string; // the booked step (activity type `visit`, stage id `site_visit`)
  visitPlural: string;
  wonLabel: string;
  /** Open stages between New and Won. Must contain one `Qualified` and one `SiteVisit` (the booked step). */
  stages: [name: string, probability: number, event?: "Qualified" | "SiteVisit"][];
  qualification: QualField[];
  fields: FieldDef[];
  compliance: string; // extra AI guardrail for regulated categories ("" when none)
  regulated: boolean; // AI autopilot & public price replies default off, explicit consent emphasised
  responseSlaMinutes: number; // lead first-response SLA for the default pipeline
  briefExample: string;
  kbHint: string;
  kbStarters: string[]; // starter knowledge-base questions (created inactive, to be answered)
  savedReplies: { shortcut: string; title: string; body: string }[];
  leadFormFields: string[];
};

const Q = (key: string, label: string, ask: string): QualField => ({ key, label, ask });
const F = (key: string, label: string, type: FieldDef["type"] = "text", options?: string[]): FieldDef => ({ key, label, type, ...(options ? { options } : {}) });
const R = (shortcut: string, title: string, body: string) => ({ shortcut, title, body });
const BASE_LEAD = ["full_name", "email", "phone_number", "city"];

const P: IndustryPreset[] = [
  /* ---------------- Service-based industries ---------------- */
  {
    key: "it_martech", group: "service", label: "Information Technology (IT) & MarTech", examples: "Software development, cloud hosting, digital marketing, AI integrations",
    business: "technology and marketing-technology company", offering: "software or digital service", projectLabel: "Solution", visit: "Demo", visitPlural: "Demos", wonLabel: "Closed won",
    stages: [["Contacted", 10], ["Discovery / qualified", 25, "Qualified"], ["Demo", 45, "SiteVisit"], ["Proposal", 65], ["Negotiation", 80]],
    qualification: [Q("need", "Need", "the problem or project they want solved"), Q("company_size", "Company size", "company size and their role"), Q("budget", "Budget", "budget range"), Q("timeline", "Timeline", "when they want to start")],
    fields: [F("company", "Company"), F("company_size", "Company size", "dropdown", ["1–10", "11–50", "51–200", "201–1000", "1000+"]), F("service_interest", "Service of interest", "multiselect", ["Software development", "Cloud hosting", "Digital marketing", "AI integration", "Support / maintenance"]), F("budget", "Budget"), F("current_stack", "Current tools / stack")],
    compliance: "", regulated: false, responseSlaMinutes: 30,
    briefExample: "Managed cloud hosting with 99.9% uptime and 24/7 support, from ৳4,500/month. Audience: SMEs moving off shared hosting. Offer: free migration this month.",
    kbHint: "services, pricing tiers, SLAs, integrations, onboarding steps and FAQs",
    kbStarters: ["What services do you offer and what do they cost?", "How long does a typical project take?", "What support and SLA do you provide?"],
    savedReplies: [R("/demo", "Book a demo", "Thanks {{first_name}}! Happy to show you how it works — which day suits you for a 20-minute demo?"), R("/pricing", "Pricing → inbox", "Hi {{first_name}}, we've sent our pricing and a short case study to your inbox 📩")],
    leadFormFields: [...BASE_LEAD, "company_name", "job_title", "service_needed", "budget"],
  },
  {
    key: "financial_services", group: "service", label: "Financial Services & Banking", examples: "Commercial banking, asset management, insurance, foreign exchange",
    business: "financial services provider (banking, insurance or investment)", offering: "financial product (account, loan, card, policy or investment)", projectLabel: "Product", visit: "Branch appointment", visitPlural: "Branch appointments", wonLabel: "Account opened / approved",
    stages: [["Contacted", 10], ["Eligibility checked", 25, "Qualified"], ["Branch appointment", 40, "SiteVisit"], ["Application submitted", 60], ["KYC & documents", 75], ["Under review / approval", 85]],
    qualification: [Q("product_interest", "Product", "which product they need (account, loan, card, insurance, investment)"), Q("customer_type", "Customer type", "whether it is personal or business"), Q("amount", "Amount", "the amount or limit they need"), Q("branch", "Preferred branch", "their preferred branch or area")],
    fields: [F("product_interest", "Product interest", "dropdown", ["Savings / current account", "Personal loan", "Home loan", "SME loan", "Credit card", "Insurance", "Investment / DPS", "Foreign exchange"]), F("customer_type", "Customer type", "dropdown", ["Personal", "Business"]), F("amount", "Amount / limit", "number"), F("monthly_income", "Monthly income band", "dropdown", ["< 30k", "30–60k", "60–150k", "150k +"]), F("branch", "Preferred branch"), F("kyc_status", "KYC status", "dropdown", ["Not started", "Documents pending", "Verified"])],
    compliance: "Regulated financial services: never promise approval, guaranteed returns, rates or fees that are not in the knowledge base; never ask for account numbers, card numbers, PINs, OTPs or passwords; direct account-specific questions to a verified private channel or branch.",
    regulated: true, responseSlaMinutes: 15,
    briefExample: "Home loan up to 75% of property value, tenure up to 25 years, decision in 7 working days. Audience: salaried professionals 28–50. Terms and conditions apply.",
    kbHint: "products, eligibility, required documents, published rates and fees, branch hours and FAQs (never personal account details)",
    kbStarters: ["What documents are needed to open an account or apply for a loan?", "What are the published interest rates and fees?", "Which branches are open and when?"],
    savedReplies: [R("/eligibility", "Eligibility → private", "Thanks {{first_name}}! Eligibility depends on a few details — we've sent you a private message. Please never share PINs or OTPs with anyone."), R("/branch", "Book branch visit", "We'd be glad to help at a branch near you, {{first_name}}. Which branch and day suit you?")],
    leadFormFields: [...BASE_LEAD, "product_interest", "customer_type", "loan_amount", "monthly_income"],
  },
  {
    key: "professional_services", group: "service", label: "Professional Services", examples: "Business consulting, legal services, accounting, engineering",
    business: "professional services firm", offering: "professional service", projectLabel: "Service", visit: "Consultation", visitPlural: "Consultations", wonLabel: "Engagement signed",
    stages: [["Contacted", 10], ["Qualified", 25, "Qualified"], ["Consultation", 45, "SiteVisit"], ["Proposal / engagement letter", 65], ["Negotiation", 80]],
    qualification: [Q("company", "Company", "their company and role"), Q("need", "Need", "the matter or problem they need help with"), Q("budget", "Budget", "budget range"), Q("timeline", "Timeline", "deadline or start date")],
    fields: [F("company", "Company"), F("service_needed", "Service needed", "dropdown", ["Consulting", "Legal", "Accounting / tax", "Audit", "Engineering", "Other"]), F("industry_of_client", "Client's industry"), F("budget", "Budget"), F("deadline", "Deadline", "date")],
    compliance: "Do not give legal, tax or engineering advice in messages; offer a consultation with a qualified professional instead.", regulated: false, responseSlaMinutes: 60,
    briefExample: "VAT & tax compliance for SMEs, fixed monthly fee from ৳8,000. Audience: owners of companies with 5–50 staff.",
    kbHint: "services, fee structure, process, team credentials, case studies and FAQs",
    kbStarters: ["What services do you provide and how are fees structured?", "What does the first consultation involve?", "Which industries do you work with?"],
    savedReplies: [R("/consult", "Book consultation", "Thanks {{first_name}}! Let's set up a short consultation — which day and time suit you?"), R("/fees", "Fees → inbox", "Hi {{first_name}}, we've sent our fee structure to your inbox 📩")],
    leadFormFields: [...BASE_LEAD, "company_name", "job_title", "service_needed"],
  },
  {
    key: "healthcare", group: "service", label: "Healthcare & Medical Services", examples: "Hospitals, clinics, telemedicine, elder care",
    business: "healthcare provider", offering: "treatment, consultation or care service", projectLabel: "Department / service", visit: "Appointment", visitPlural: "Appointments", wonLabel: "Patient treated / admitted",
    stages: [["Contacted", 15], ["Triage / qualified", 35, "Qualified"], ["Appointment booked", 60, "SiteVisit"], ["Consultation done", 80]],
    qualification: [Q("service", "Service / department", "which service, department or doctor they need"), Q("preferred_date", "Preferred date", "their preferred date and time"), Q("branch", "Branch", "which branch or telemedicine"), Q("payment", "Payment", "insurance, corporate panel or self-pay")],
    fields: [F("department", "Department / specialty", "dropdown", ["General medicine", "Cardiology", "Gynae & obstetrics", "Paediatrics", "Orthopaedics", "Dental", "Diagnostics", "Telemedicine", "Elder care"]), F("preferred_doctor", "Preferred doctor"), F("preferred_date", "Preferred date", "date"), F("payment_type", "Payment type", "dropdown", ["Self-pay", "Insurance", "Corporate panel"]), F("patient_age", "Patient age", "number")],
    compliance: "Never give diagnosis, treatment or medication advice; for emergencies tell the person to call emergency services or come to the emergency department immediately; never ask for or repeat medical details in public replies.",
    regulated: true, responseSlaMinutes: 10,
    briefExample: "Free health check-up week at our Dhanmondi branch, 10–16 March: blood sugar, BP and BMI. Audience: adults 35+. Book by phone or WhatsApp.",
    kbHint: "services, doctors' schedules, fees, branches, insurance panels and FAQs (never medical advice)",
    kbStarters: ["Which doctors are available and when?", "What are the consultation and test fees?", "Which insurance and corporate panels do you accept?"],
    savedReplies: [R("/appointment", "Book appointment", "Thanks {{first_name}}! Which department and preferred date should we book for you?"), R("/emergency", "Emergency", "If this is an emergency please call 999 or come to our emergency department right away.")],
    leadFormFields: [...BASE_LEAD, "service_needed", "preferred_date", "preferred_doctor"],
  },
  {
    key: "travel_hospitality", group: "service", label: "Travel, Hospitality & Tourism", examples: "Airlines, hotels, resorts, travel booking, car rentals",
    business: "travel and hospitality company", offering: "trip, stay or travel package", projectLabel: "Package / property", visit: "Consultation", visitPlural: "Consultations", wonLabel: "Booked",
    stages: [["Contacted", 10], ["Requirements captured", 30, "Qualified"], ["Quote / consultation", 50, "SiteVisit"], ["Payment pending", 80]],
    qualification: [Q("destination", "Destination", "where they want to go or stay"), Q("travel_dates", "Travel dates", "their travel or check-in dates"), Q("travellers", "Travellers", "how many people"), Q("budget", "Budget", "budget per person")],
    fields: [F("destination", "Destination"), F("travel_dates", "Travel dates"), F("travellers", "Travellers", "number"), F("trip_type", "Trip type", "dropdown", ["Flight", "Hotel / resort", "Package tour", "Car rental", "Visa assistance", "Umrah / Hajj"]), F("budget", "Budget per person")],
    compliance: "", regulated: false, responseSlaMinutes: 20,
    briefExample: "Cox's Bazar 3-night family package from ৳18,500 per person, hotel + transport. Audience: families in Dhaka.",
    kbHint: "packages, prices, inclusions, availability, visa help, cancellation policy and FAQs",
    kbStarters: ["What is included in the package price?", "What is the cancellation and refund policy?", "Do you help with visas?"],
    savedReplies: [R("/quote", "Quote → inbox", "Thanks {{first_name}}! We've sent you a quote in your inbox 📩 — tell us your dates to confirm availability."), R("/dates", "Ask dates", "Lovely choice! Which dates and how many travellers, {{first_name}}?")],
    leadFormFields: [...BASE_LEAD, "destination", "travel_dates", "travellers"],
  },
  {
    key: "property_facility", group: "service", label: "Property & Facility Management (IFM)", examples: "Integrated facility management, real estate maintenance, property leasing",
    business: "property and facility management company", offering: "facility management or leasing service", projectLabel: "Site / property", visit: "Site survey", visitPlural: "Site surveys", wonLabel: "Contract signed",
    stages: [["Contacted", 10], ["Qualified", 25, "Qualified"], ["Site survey", 45, "SiteVisit"], ["Proposal / quotation", 65], ["Negotiation", 80]],
    qualification: [Q("property_type", "Property type", "the property type and size"), Q("services_needed", "Services", "which services they need (cleaning, security, maintenance, leasing)"), Q("location", "Location", "where the property is"), Q("start_date", "Start date", "when they want to start")],
    fields: [F("property_type", "Property type", "dropdown", ["Office", "Residential", "Retail / mall", "Industrial / warehouse", "Hospital", "Education"]), F("area_sqft", "Area (sqft)", "number"), F("services_needed", "Services needed", "multiselect", ["Cleaning", "Security", "MEP maintenance", "Landscaping", "Leasing", "Pest control"]), F("contract_term", "Contract term", "dropdown", ["Monthly", "1 year", "2–3 years"]), F("location", "Location")],
    compliance: "", regulated: false, responseSlaMinutes: 60,
    briefExample: "Integrated facility management for offices: cleaning, security and MEP maintenance under one contract. Audience: admin & facility managers.",
    kbHint: "services, coverage areas, pricing approach, certifications, response times and FAQs",
    kbStarters: ["Which services are covered in an integrated FM contract?", "Which areas do you serve?", "How fast do you respond to maintenance requests?"],
    savedReplies: [R("/survey", "Book site survey", "Thanks {{first_name}}! We'd like to survey the site to quote accurately — which day suits you?"), R("/services", "Services list", "We cover cleaning, security, MEP maintenance, landscaping and leasing. Which do you need, {{first_name}}?")],
    leadFormFields: [...BASE_LEAD, "company_name", "property_type", "area_sqft", "services_needed"],
  },
  {
    key: "transport_logistics", group: "service", label: "Transportation & Logistics", examples: "Freight forwarding, supply chain management, international shipping",
    business: "logistics and freight company", offering: "shipping or logistics service", projectLabel: "Lane / service", visit: "Rate quote meeting", visitPlural: "Rate quote meetings", wonLabel: "Shipment booked",
    stages: [["Contacted", 10], ["Shipment details captured", 30, "Qualified"], ["Rate quote meeting", 50, "SiteVisit"], ["Quote sent", 65], ["Negotiation", 80]],
    qualification: [Q("route", "Route", "origin and destination"), Q("cargo", "Cargo", "cargo type, weight and volume"), Q("mode", "Mode", "sea, air, road or multimodal"), Q("ready_date", "Ready date", "when the cargo is ready")],
    fields: [F("origin", "Origin"), F("destination", "Destination"), F("mode", "Mode", "dropdown", ["Sea FCL", "Sea LCL", "Air", "Road", "Courier", "Multimodal"]), F("cargo_type", "Cargo type"), F("weight_kg", "Weight (kg)", "number"), F("incoterm", "Incoterm", "dropdown", ["EXW", "FOB", "CIF", "DAP", "DDP"])],
    compliance: "", regulated: false, responseSlaMinutes: 30,
    briefExample: "Weekly LCL consolidation Chattogram → Rotterdam, 28-day transit, door-to-door available. Audience: RMG exporters.",
    kbHint: "lanes, transit times, rate basis, documentation, customs support and FAQs",
    kbStarters: ["Which lanes and transit times do you offer?", "What documents are needed for export?", "How are rates calculated?"],
    savedReplies: [R("/quote", "Ask shipment details", "Thanks {{first_name}}! To quote, please share origin, destination, cargo type, weight/volume and ready date."), R("/track", "Tracking", "Please share your booking or AWB/BL number privately and we'll update you right away.")],
    leadFormFields: [...BASE_LEAD, "company_name", "origin", "destination", "cargo_type"],
  },
  {
    key: "media_entertainment", group: "service", label: "Media & Entertainment", examples: "Cinema, sports broadcasting, streaming services, event management",
    business: "media and entertainment company", offering: "ticket, subscription, sponsorship or event", projectLabel: "Event / title", visit: "Event / screening", visitPlural: "Events / screenings", wonLabel: "Purchased / signed",
    stages: [["Contacted", 10], ["Interested", 30, "Qualified"], ["Event / screening", 50, "SiteVisit"], ["Proposal / checkout", 75]],
    qualification: [Q("interest", "Interest", "which event, show, plan or sponsorship"), Q("quantity", "Quantity", "how many tickets or seats"), Q("date", "Date", "preferred date or show time"), Q("budget", "Budget", "budget")],
    fields: [F("interest_type", "Interest", "dropdown", ["Tickets", "Subscription", "Sponsorship", "Advertising", "Event booking"]), F("event_name", "Event / title"), F("tickets", "Tickets", "number"), F("company", "Company (sponsors)")],
    compliance: "", regulated: false, responseSlaMinutes: 30,
    briefExample: "Live screening of the final this Friday, giant screen + food deals, tickets from ৳500. Audience: sports fans 18–35.",
    kbHint: "events, schedules, ticket prices, subscription plans, sponsorship packages and FAQs",
    kbStarters: ["What are the show times and ticket prices?", "What subscription plans do you offer?", "What sponsorship packages are available?"],
    savedReplies: [R("/tickets", "Tickets link", "Thanks {{first_name}}! Tickets are available here — which show time would you like?"), R("/sponsor", "Sponsorship deck", "We've sent our sponsorship deck to your inbox 📩")],
    leadFormFields: [...BASE_LEAD, "interest_type", "event_name", "company_name"],
  },
  {
    key: "telecom", group: "service", label: "Telecommunications", examples: "Corporate internet, mobile networks, satellite communications",
    business: "telecommunications provider", offering: "connectivity plan or service", projectLabel: "Plan / service", visit: "Site survey", visitPlural: "Site surveys", wonLabel: "Connection activated",
    stages: [["Contacted", 10], ["Coverage checked", 30, "Qualified"], ["Site survey", 45, "SiteVisit"], ["Proposal", 65], ["Installation scheduled", 85]],
    qualification: [Q("service", "Service", "which service (internet, mobile, satellite, enterprise)"), Q("location", "Location", "installation address or area"), Q("bandwidth", "Bandwidth", "bandwidth or number of lines"), Q("customer_type", "Customer type", "home or business")],
    fields: [F("service_type", "Service", "dropdown", ["Home internet", "Corporate internet", "Dedicated line", "Mobile / SIM", "Satellite", "Cloud PBX"]), F("bandwidth_mbps", "Bandwidth (Mbps)", "number"), F("lines", "Number of lines", "number"), F("install_address", "Installation address"), F("coverage_status", "Coverage", "dropdown", ["Unknown", "Covered", "Not covered"])],
    compliance: "Never ask for SIM PINs, OTPs or national ID numbers in chat; account changes go through verified channels.", regulated: false, responseSlaMinutes: 20,
    briefExample: "Corporate internet 100 Mbps dedicated with 99.5% SLA from ৳18,000/month, free installation. Audience: offices in Gulshan & Banani.",
    kbHint: "plans, coverage areas, installation timelines, SLAs, prices and FAQs",
    kbStarters: ["Which areas have coverage?", "What plans and prices do you offer?", "How long does installation take?"],
    savedReplies: [R("/coverage", "Coverage check", "Thanks {{first_name}}! Please share your address or area and we'll check coverage."), R("/plans", "Plans → inbox", "We've sent our plans and prices to your inbox 📩")],
    leadFormFields: [...BASE_LEAD, "service_type", "install_address", "company_name"],
  },

  /* ---------------- Product & manufacturing industries ---------------- */
  {
    key: "consumer_electronics", group: "product", label: "Consumer Electronics & Hardware", examples: "Laptops, networking equipment, microchips, mobile devices",
    business: "electronics and hardware company", offering: "device or hardware product", projectLabel: "Product / model", visit: "Store visit / demo", visitPlural: "Store visits / demos", wonLabel: "Purchased",
    stages: [["Contacted", 15], ["Requirement captured", 35, "Qualified"], ["Store visit / demo", 55, "SiteVisit"], ["Quotation", 75]],
    qualification: [Q("product", "Product", "which product or model"), Q("quantity", "Quantity", "quantity (retail or bulk)"), Q("budget", "Budget", "budget"), Q("customer_type", "Customer type", "personal or business / reseller")],
    fields: [F("product_category", "Category", "dropdown", ["Laptop", "Desktop", "Mobile", "Networking", "Components", "Accessories"]), F("model", "Model"), F("quantity", "Quantity", "number"), F("customer_type", "Customer type", "dropdown", ["Retail", "Corporate", "Reseller"]), F("warranty_need", "Warranty / service need")],
    compliance: "", regulated: false, responseSlaMinutes: 20,
    briefExample: "Business laptops with 3-year warranty, corporate pricing for 10+ units. Audience: IT managers.",
    kbHint: "products, specs, stock, prices, warranty, service centres and FAQs",
    kbStarters: ["Is this model in stock and what does it cost?", "What warranty and service do you provide?", "Do you offer corporate or bulk pricing?"],
    savedReplies: [R("/stock", "Stock & price", "Thanks {{first_name}}! We've sent current stock and price to your inbox 📩"), R("/bulk", "Bulk quote", "For bulk orders please share model and quantity — we'll send a corporate quote.")],
    leadFormFields: [...BASE_LEAD, "product_category", "model", "quantity"],
  },
  {
    key: "real_estate", group: "product", label: "Real Estate Development & Construction", examples: "Residential housing, commercial buildings, infrastructure projects",
    business: "real estate developer", offering: "property", projectLabel: "Project", visit: "Site visit", visitPlural: "Site visits", wonLabel: "Won (Booked)",
    stages: [["Contacted", 10], ["Qualified", 25, "Qualified"], ["Site Visit", 50, "SiteVisit"], ["Negotiation", 75]],
    qualification: [Q("budget", "Budget", "their budget"), Q("location", "Preferred location", "preferred location"), Q("timeline", "Purchase timeline", "purchase timeline"), Q("unit_type", "Unit type", "unit type (e.g. 3 bed)")],
    fields: [F("budget", "Budget", "dropdown", ["< 1 Cr", "1–2 Cr", "2–3 Cr", "3 Cr +"]), F("location", "Preferred location"), F("timeline", "Purchase timeline", "dropdown", ["Immediately", "Within 3 months", "3–6 months", "6–12 months"]), F("unit_type", "Unit type", "multiselect", ["2 bed", "3 bed", "4 bed", "Duplex", "Commercial"]), F("handover_date", "Handover date", "date")],
    compliance: "", regulated: false, responseSlaMinutes: 5,
    briefExample: "Gulshan Heights: 3 & 4 bed lake-view apartments in Gulshan 2, handover Dec 2027, RAJUK approved, 70% bank loan support. Audience: families and NRB investors. Offer: book this month, save up to ৳10 lakh.",
    kbHint: "prices, discounts, payment plans, handover dates, locations and FAQs",
    kbStarters: ["What are the prices per unit type?", "What is the payment plan?", "When is handover?"],
    savedReplies: [R("/price", "Price → inbox", "Hi {{first_name}}! Thanks for your interest 😊 We've sent you the price list in your inbox."), R("/visit", "Book a visit", "We'd love to show you around, {{first_name}}! Which day suits you for a site visit?")],
    leadFormFields: [...BASE_LEAD, "first_name", "last_name", "budget", "preferred_location", "when_are_you_planning_to_buy", "unit_type"],
  },
  {
    key: "automotive", group: "product", label: "Automotive & Vehicle Manufacturing", examples: "Electric vehicles, commercial auto parts, heavy equipment",
    business: "automotive and vehicle company", offering: "vehicle, part or equipment", projectLabel: "Model", visit: "Test drive", visitPlural: "Test drives", wonLabel: "Sold / delivered",
    stages: [["Contacted", 10], ["Qualified", 25, "Qualified"], ["Test drive / demo", 50, "SiteVisit"], ["Quotation & financing", 70], ["Negotiation", 85]],
    qualification: [Q("model", "Model", "which model, part or equipment"), Q("budget", "Budget", "budget"), Q("financing", "Financing", "whether they need financing or trade-in"), Q("timeline", "Timeline", "when they plan to buy")],
    fields: [F("model", "Model / part"), F("vehicle_type", "Type", "dropdown", ["Passenger car", "EV", "Commercial vehicle", "Heavy equipment", "Auto parts"]), F("financing", "Financing", "dropdown", ["Cash", "Bank loan", "Lease"]), F("trade_in", "Trade-in vehicle"), F("fleet_size", "Fleet size", "number")],
    compliance: "", regulated: false, responseSlaMinutes: 15,
    briefExample: "New hybrid SUV launch: test drives this weekend, 0% financing for 12 months. Audience: professionals 30–55.",
    kbHint: "models, prices, financing, trade-in, parts availability, service and FAQs",
    kbStarters: ["What is the on-road price?", "Which financing options are available?", "Do you accept trade-ins?"],
    savedReplies: [R("/testdrive", "Book test drive", "Thanks {{first_name}}! Which day suits you for a test drive?"), R("/finance", "Financing", "We offer bank loans and leasing — we've sent options to your inbox 📩")],
    leadFormFields: [...BASE_LEAD, "model_of_interest", "trade_in", "financing"],
  },
  {
    key: "electrical_industrial", group: "product", label: "Electrical Equipment & Industrial Supplies", examples: "Electrical cables (e.g. RM cables), switchgear, power generation systems",
    business: "electrical equipment and industrial supply manufacturer", offering: "cable, switchgear or power product", projectLabel: "Product line", visit: "Technical meeting", visitPlural: "Technical meetings", wonLabel: "Order confirmed",
    stages: [["Contacted", 10], ["Requirement / BOQ received", 30, "Qualified"], ["Technical meeting", 45, "SiteVisit"], ["Quotation / tender", 65], ["Negotiation", 80]],
    qualification: [Q("product", "Product", "which product and specification (size, rating, standard)"), Q("quantity", "Quantity", "quantity or BOQ"), Q("project", "Project", "project or end use"), Q("delivery", "Delivery", "required delivery date and location")],
    fields: [F("product_line", "Product line", "dropdown", ["Power cable", "Building wire", "Control cable", "Switchgear", "Transformer", "Generator", "Accessories"]), F("specification", "Specification / standard"), F("quantity", "Quantity"), F("customer_type", "Customer type", "dropdown", ["Contractor", "Dealer / distributor", "Industry", "Government / tender", "Retail"]), F("delivery_date", "Delivery date", "date")],
    compliance: "Do not confirm technical ratings, certifications or prices that are not in the knowledge base; route specification questions to the technical team.", regulated: false, responseSlaMinutes: 60,
    briefExample: "BSTI & IEC certified power cables, ready stock in all common sizes, dealer pricing available. Audience: electrical contractors and dealers.",
    kbHint: "product ranges, specifications, certifications, dealer network, lead times and FAQs",
    kbStarters: ["Which sizes and standards are available?", "What certifications do your products have?", "Where are your dealers?"],
    savedReplies: [R("/boq", "Ask for BOQ", "Thanks {{first_name}}! Please share your BOQ or required sizes and quantity and we'll send a quotation."), R("/dealer", "Nearest dealer", "Please share your area and we'll connect you with the nearest dealer.")],
    leadFormFields: [...BASE_LEAD, "company_name", "product_line", "quantity", "customer_type"],
  },
  {
    key: "agriculture_food", group: "product", label: "Agriculture & Food Production", examples: "Commercial farming, food processing, consumer staples",
    business: "agriculture and food company", offering: "food or agricultural product", projectLabel: "Product", visit: "Sample / farm visit", visitPlural: "Sample / farm visits", wonLabel: "Order confirmed",
    stages: [["Contacted", 10], ["Qualified", 30, "Qualified"], ["Sample / farm visit", 50, "SiteVisit"], ["Quotation", 70], ["Negotiation", 85]],
    qualification: [Q("product", "Product", "which product"), Q("quantity", "Quantity", "quantity and frequency"), Q("buyer_type", "Buyer type", "retail, wholesale, distributor or export"), Q("delivery_area", "Delivery area", "delivery location")],
    fields: [F("product", "Product"), F("buyer_type", "Buyer type", "dropdown", ["Retail", "Wholesale", "Distributor", "Export", "HoReCa"]), F("monthly_volume", "Monthly volume"), F("delivery_area", "Delivery area"), F("certification_need", "Certification need (e.g. halal, organic)")],
    compliance: "Do not make health claims that are not in the knowledge base.", regulated: false, responseSlaMinutes: 60,
    briefExample: "Fresh farm eggs and poultry delivered daily to restaurants in Dhaka, contract pricing for 6 months. Audience: restaurant owners.",
    kbHint: "products, pack sizes, prices, minimum orders, delivery areas, certifications and FAQs",
    kbStarters: ["What is the minimum order and price?", "Which areas do you deliver to?", "Which certifications do you have?"],
    savedReplies: [R("/order", "Order details", "Thanks {{first_name}}! Please share product, quantity and delivery area to get a quote."), R("/sample", "Request sample", "We can arrange a sample — please share your address and business name.")],
    leadFormFields: [...BASE_LEAD, "company_name", "product", "buyer_type", "monthly_volume"],
  },
  {
    key: "energy_utilities", group: "product", label: "Energy, Utilities & Renewables", examples: "Solar grids, oil & gas exploration, electricity production",
    business: "energy and renewables company", offering: "energy system or supply contract", projectLabel: "Project / system", visit: "Site assessment", visitPlural: "Site assessments", wonLabel: "Contract signed",
    stages: [["Contacted", 10], ["Qualified", 25, "Qualified"], ["Site assessment", 45, "SiteVisit"], ["Proposal / feasibility", 65], ["Negotiation", 80]],
    qualification: [Q("need", "Need", "what they need (solar, backup, supply contract)"), Q("load", "Load", "monthly consumption or load (kW)"), Q("site", "Site", "site type and location"), Q("budget", "Budget / financing", "budget or financing need")],
    fields: [F("solution", "Solution", "dropdown", ["Rooftop solar", "Solar irrigation", "Mini-grid", "Generator / backup", "Supply contract", "EPC project"]), F("load_kw", "Load (kW)", "number"), F("monthly_bill", "Monthly electricity bill", "number"), F("site_type", "Site type", "dropdown", ["Home", "Factory", "Commercial", "Agriculture", "Government"]), F("financing", "Financing", "dropdown", ["Cash", "Loan", "PPA / lease"])],
    compliance: "Do not promise specific savings or payback periods unless they are in the knowledge base.", regulated: false, responseSlaMinutes: 60,
    briefExample: "Rooftop solar for factories: cut your electricity bill, net-metering support, financing available. Audience: factory owners.",
    kbHint: "solutions, system sizes, indicative pricing, financing, net metering, warranties and FAQs",
    kbStarters: ["How is system size and price estimated?", "Is financing available?", "What warranties apply?"],
    savedReplies: [R("/assess", "Site assessment", "Thanks {{first_name}}! Share your monthly bill and location and we'll arrange a free site assessment."), R("/finance", "Financing", "We offer loan and PPA options — details sent to your inbox 📩")],
    leadFormFields: [...BASE_LEAD, "company_name", "solution", "monthly_bill", "site_type"],
  },
  {
    key: "pharma_meddevices", group: "product", label: "Pharmaceuticals & Medical Devices", examples: "Drug manufacturing, laboratory equipment, surgical tools",
    business: "pharmaceutical and medical device company", offering: "pharmaceutical or medical device product", projectLabel: "Product", visit: "Product presentation", visitPlural: "Product presentations", wonLabel: "Order / listing confirmed",
    stages: [["Contacted", 10], ["Qualified (HCP / institution)", 25, "Qualified"], ["Product presentation", 45, "SiteVisit"], ["Quotation / tender", 65], ["Procurement approval", 80]],
    qualification: [Q("institution", "Institution", "their institution or pharmacy and role"), Q("product", "Product", "which product or category"), Q("quantity", "Quantity", "quantity or annual requirement"), Q("procurement", "Procurement", "procurement process or tender timeline")],
    fields: [F("customer_type", "Customer type", "dropdown", ["Hospital", "Clinic", "Pharmacy", "Distributor", "Laboratory", "Government"]), F("product_category", "Product category", "dropdown", ["Medicines", "Lab equipment", "Surgical instruments", "Diagnostics", "Consumables"]), F("annual_requirement", "Annual requirement"), F("tender_date", "Tender date", "date"), F("license_no", "Drug / trade licence no.")],
    compliance: "Regulated healthcare products: never give dosage, treatment or off-label advice to patients; only state approved indications and claims from the knowledge base; route adverse-event reports to the pharmacovigilance team.",
    regulated: true, responseSlaMinutes: 60,
    briefExample: "Surgical instruments with CE marking, 2-year warranty, tender support for hospitals. Audience: hospital procurement and surgeons.",
    kbHint: "product catalogue, approved indications, registrations, pricing for institutions, distributors and FAQs (no patient medical advice)",
    kbStarters: ["Which products and registrations do you have?", "How do hospitals order or tender?", "Who are your distributors?"],
    savedReplies: [R("/catalogue", "Catalogue → inbox", "Thanks {{first_name}}! We've sent our catalogue and registration details to your inbox 📩"), R("/ae", "Adverse event", "Thank you for reporting this. Our pharmacovigilance team will contact you privately — please share your phone number in a private message.")],
    leadFormFields: [...BASE_LEAD, "institution_name", "customer_type", "product_category"],
  },
  {
    key: "retail_ecommerce", group: "product", label: "Retail & E-commerce", examples: "Department stores, online marketplaces, consumer goods distribution",
    business: "retail and e-commerce brand", offering: "product", projectLabel: "Product / collection", visit: "Store visit", visitPlural: "Store visits", wonLabel: "Purchased",
    stages: [["Contacted", 15], ["Interested", 35, "Qualified"], ["Cart / store visit", 55, "SiteVisit"], ["Order placed", 85]],
    qualification: [Q("product", "Product", "which product"), Q("size_variant", "Size / variant", "size, colour or variant"), Q("budget", "Budget", "budget"), Q("delivery_area", "Delivery area", "delivery area")],
    fields: [F("product_interest", "Product interest"), F("size_variant", "Size / variant"), F("order_value", "Order value", "number"), F("delivery_area", "Delivery area"), F("channel_pref", "Buys via", "dropdown", ["Online", "Store", "Both"])],
    compliance: "", regulated: false, responseSlaMinutes: 10,
    briefExample: "Eid collection: handloom panjabi from ৳2,490, free delivery inside Dhaka. Audience: men 22–45.",
    kbHint: "prices, stock, sizes, delivery charges and times, returns and FAQs",
    kbStarters: ["What sizes and colours are available?", "What are the delivery charges and times?", "What is the return policy?"],
    savedReplies: [R("/price", "Price → inbox", "Hi {{first_name}}! Price and available sizes sent to your inbox 📩"), R("/delivery", "Delivery info", "We deliver across Bangladesh — inside Dhaka 1–2 days, outside 3–5 days.")],
    leadFormFields: [...BASE_LEAD, "product_interest", "size_variant"],
  },

  /* ---------------- fallback ---------------- */
  {
    key: "general", group: "other", label: "Other / general", examples: "Any other business",
    business: "business", offering: "product or service", projectLabel: "Interest", visit: "Appointment", visitPlural: "Appointments", wonLabel: "Won",
    stages: [["Contacted", 10], ["Qualified", 25, "Qualified"], ["Appointment", 50, "SiteVisit"], ["Negotiation", 75]],
    qualification: [Q("need", "Need", "what they are looking for"), Q("budget", "Budget", "their budget"), Q("timeline", "Timeline", "when they want to buy or start"), Q("location", "Location", "where they are based")],
    fields: [F("need", "Need"), F("budget", "Budget"), F("timeline", "Timeline", "dropdown", ["Immediately", "Within 1 month", "1–3 months", "Later"])],
    compliance: "", regulated: false, responseSlaMinutes: 15,
    briefExample: "Product, audience, offer and proof points — e.g. “Spring sale: 20% off all plans until 31 March. Audience: small business owners in Dhaka.”",
    kbHint: "prices, offers, opening hours, locations, delivery and FAQs",
    kbStarters: ["What are your prices?", "Where are you located and when are you open?", "How do I get started?"],
    savedReplies: [R("/info", "Details → inbox", "Thanks {{first_name}}! We've sent the details to your inbox 📩"), R("/book", "Book appointment", "Which day and time suit you, {{first_name}}?")],
    leadFormFields: [...BASE_LEAD, "what_are_you_looking_for", "budget"],
  },
];

export const INDUSTRIES: Record<string, IndustryPreset> = Object.fromEntries(P.map((p) => [p.key, p]));
/** Keys used before the full category list existed. */
const ALIASES: Record<string, string> = { services: "professional_services", retail: "retail_ecommerce", travel: "travel_hospitality", education: "general" };
export const normalizeIndustry = (k?: string | null) => (k && INDUSTRIES[k] ? k : k && ALIASES[k] ? ALIASES[k]! : "general");

export const INDUSTRY_GROUPS = [
  { label: "Service-based industries", items: P.filter((p) => p.group === "service") },
  { label: "Product & manufacturing industries", items: P.filter((p) => p.group === "product") },
  { label: "Other", items: P.filter((p) => p.group === "other") },
].map((g) => ({ label: g.label, options: g.items.map((p) => ({ value: p.key, label: p.label, examples: p.examples })) }));
export const INDUSTRY_OPTIONS = INDUSTRY_GROUPS.flatMap((g) => g.options);

/** Preset for a workspace; `visitLabel` lets a workspace rename the booked step. */
export function industryOf(settings: Pick<WorkspaceSettings, "industry" | "visitLabel"> | null | undefined): IndustryPreset {
  const p = INDUSTRIES[normalizeIndustry(settings?.industry)]!;
  const v = settings?.visitLabel?.trim();
  return v ? { ...p, visit: v, visitPlural: /s$/i.test(v) ? v : `${v}s` } : p;
}

/** Full funnel for an industry. Stable ids: new · contacted… · qualified · site_visit · … · won · lost. */
export function industryStages(key?: string | null): PipelineStage[] {
  const p = INDUSTRIES[normalizeIndustry(key)]!;
  const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
  const open: PipelineStage[] = p.stages.map(([name, probability, event], i) => ({
    id: event === "Qualified" ? "qualified" : event === "SiteVisit" ? "site_visit" : slug(name) || `stage_${i}`,
    name, order: i + 1, probability, kind: "open" as const, ...(event ? { conversionEvent: event } : {}),
  }));
  return [
    { id: "new", name: "New", order: 0, probability: 5, kind: "open" },
    ...open,
    { id: "won", name: p.wonLabel, order: open.length + 1, probability: 100, kind: "won", conversionEvent: "Won" },
    { id: "lost", name: "Lost", order: open.length + 2, probability: 0, kind: "lost" },
  ];
}

/** Client-safe subset sent to the UI (via /team). */
export const industryForClient = (s: Pick<WorkspaceSettings, "industry" | "visitLabel"> | null | undefined) => {
  const p = industryOf(s);
  return { key: p.key, label: p.label, group: p.group, visit: p.visit, visitPlural: p.visitPlural, briefExample: p.briefExample, kbHint: p.kbHint, offering: p.offering, projectLabel: p.projectLabel, regulated: p.regulated };
};
