// ProfitPulse GST Pro — Complete SaaS Application
// By Vatsa Traders | FY 2025-26 | AI-Powered | Unlimited Invoices
// SEO, Schema.org, GST Rules 2026 compliant

const { useState, useEffect, useRef, useCallback } = React;

// ── CONFIG ────────────────────────────────────────────────────────────────────
const CONFIG = {
  COMPANY: "Vatsa Traders",
  PRODUCT: "ProfitPulse GST Pro",
  FY: "2025-26",
  VERSION: "3.0",
  GSTIN_VATSA: "06BENPS9060N1ZM",
  ADDRESS: "7A, SRS Flats, Bali Nagar, Near Agra Chowk, Palwal, Haryana — 121102",
  EMAIL: "kuwarpal@gmail.com",
  STATE: "Haryana",
  STATE_CODE: "06",
  SAC: "998314",
  GST_RATE: 18,
  // Replace with your actual Anthropic API key or proxy endpoint
  AI_ENDPOINT: "https://api.anthropic.com/v1/messages",
  AI_KEY: "YOUR_ANTHROPIC_API_KEY", // ← Replace this
  // Razorpay — replace with your actual key from Razorpay Dashboard
  RAZORPAY_KEY: "rzp_test_YourKeyHere", // ← Replace with rzp_live_XXXX for production
  RAZORPAY_NAME: "Vatsa Traders",
  RAZORPAY_DESC: "ProfitPulse GST Pro Subscription",
  RAZORPAY_LOGO: "https://profitpulseglobal.com/wp-content/uploads/2025/11/ProfitPulse-Global-Logo.png",
};

// ── STYLES ────────────────────────────────────────────────────────────────────
const STYLES = `
  :root {
    --navy:#0F1E45; --indigo:#1A3A8F; --teal:#00B8A9; --teal-light:#E0FAF8;
    --amber:#F5A623; --green:#22C55E; --red:#EF4444; --yellow:#EAB308;
    --slate0:#F8FAFC; --slate1:#EFF3F9; --slate2:#CBD5E1; --slate3:#94A3B8;
    --slate8:#1E293B; --white:#FFFFFF;
    --shadow:0 1px 4px rgba(0,0,0,.07); --shadow-md:0 4px 20px rgba(0,0,0,.11);
    --r:10px; --rs:6px;
  }
  *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
  body{font-family:'Inter',system-ui,sans-serif;background:var(--slate0);color:var(--slate8);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}
  /* ── Layout */
  .app{display:flex;height:100vh;overflow:hidden}
  .sidebar{width:242px;min-width:242px;background:var(--navy);display:flex;flex-direction:column;overflow-y:auto;overflow-x:hidden;transition:width .2s}
  .main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0}
  .topbar{height:56px;background:var(--white);border-bottom:1px solid var(--slate1);display:flex;align-items:center;padding:0 24px;gap:10px;flex-shrink:0;box-shadow:var(--shadow)}
  .content{flex:1;overflow-y:auto;padding:24px}
  /* ── Sidebar */
  .sb-logo{padding:18px 16px 14px;border-bottom:1px solid rgba(255,255,255,.08)}
  .sb-logo-title{color:#fff;font-size:14px;font-weight:800;line-height:1.25;letter-spacing:-.01em}
  .sb-logo-title span{color:var(--teal)}
  .sb-logo-sub{color:rgba(255,255,255,.38);font-size:10px;margin-top:3px;font-weight:500}
  .sb-fy{background:rgba(0,184,169,.18);border:1px solid rgba(0,184,169,.3);color:var(--teal);font-size:10px;font-weight:700;padding:2px 8px;border-radius:99px;display:inline-block;margin-top:6px}
  .sb-section{padding:14px 16px 4px;color:rgba(255,255,255,.25);font-size:9px;font-weight:700;letter-spacing:.1em;text-transform:uppercase}
  .sb-item{display:flex;align-items:center;gap:10px;padding:9px 14px;margin:1px 8px;border-radius:var(--rs);cursor:pointer;color:rgba(255,255,255,.58);font-size:12.5px;font-weight:500;transition:all .15s;user-select:none}
  .sb-item:hover{background:rgba(255,255,255,.07);color:#fff}
  .sb-item.active{background:var(--teal);color:#fff;font-weight:600}
  .sb-item .si{font-size:15px;width:20px;text-align:center;flex-shrink:0}
  .sb-badge{margin-left:auto;background:var(--amber);color:var(--navy);font-size:9px;font-weight:800;padding:1px 6px;border-radius:99px;flex-shrink:0}
  .sb-footer{margin-top:auto;padding:14px 16px;border-top:1px solid rgba(255,255,255,.07)}
  .sb-footer p{color:rgba(255,255,255,.25);font-size:10px;line-height:1.6}
  /* ── Topbar */
  .tb-title{font-size:14px;font-weight:700;color:var(--slate8)}
  .tb-sub{font-size:11px;color:var(--slate3)}
  .tb-spacer{flex:1}
  .fy-chip{background:var(--teal-light);border:1px solid rgba(0,184,169,.3);color:#0F766E;font-size:11px;font-weight:700;padding:4px 10px;border-radius:99px}
  .tb-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--indigo),var(--teal));color:#fff;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;cursor:pointer;flex-shrink:0}
  /* ── Page header */
  .pg-hd{margin-bottom:20px}
  .pg-hd h2{font-size:19px;font-weight:800;color:var(--slate8);letter-spacing:-.02em}
  .pg-hd p{font-size:12.5px;color:var(--slate3);margin-top:2px}
  /* ── Cards */
  .card{background:var(--white);border-radius:var(--r);box-shadow:var(--shadow);padding:18px}
  .card-hd{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;flex-wrap:wrap;gap:8px}
  .card-hd h3{font-size:13px;font-weight:700;color:var(--slate8)}
  .card-link{font-size:12px;color:var(--teal);cursor:pointer;font-weight:600}
  /* ── Stat cards */
  .stat-card{background:var(--white);border-radius:var(--r);box-shadow:var(--shadow);padding:18px;border-left:3px solid transparent;transition:box-shadow .15s}
  .stat-card:hover{box-shadow:var(--shadow-md)}
  .stat-card.c-teal{border-left-color:var(--teal)}
  .stat-card.c-indigo{border-left-color:var(--indigo)}
  .stat-card.c-amber{border-left-color:var(--amber)}
  .stat-card.c-red{border-left-color:var(--red)}
  .stat-card.c-green{border-left-color:var(--green)}
  .stat-lbl{font-size:10px;color:var(--slate3);font-weight:600;text-transform:uppercase;letter-spacing:.07em;margin-bottom:6px}
  .stat-val{font-size:21px;font-weight:800;color:var(--slate8);font-variant-numeric:tabular-nums;letter-spacing:-.02em}
  .stat-sub{font-size:11px;color:var(--slate3);margin-top:3px}
  .stat-delta{font-size:11px;font-weight:700;margin-top:4px}
  .delta-up{color:var(--green)} .delta-dn{color:var(--red)}
  /* ── Grids */
  .g4{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:18px}
  .g3{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:18px}
  .g2{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-bottom:18px}
  /* ── Tables */
  .tbl-wrap{overflow-x:auto;border-radius:var(--rs)}
  table{width:100%;border-collapse:collapse;font-size:12.5px}
  th{background:var(--slate0);color:var(--slate3);font-size:10px;font-weight:700;letter-spacing:.07em;text-transform:uppercase;padding:9px 12px;text-align:left;border-bottom:1px solid var(--slate1);white-space:nowrap}
  td{padding:10px 12px;border-bottom:1px solid var(--slate1);color:var(--slate8);vertical-align:middle}
  tr:last-child td{border-bottom:none}
  tr:hover td{background:var(--slate0)}
  .mono{font-family:'Courier New',monospace;font-size:11.5px}
  /* ── Pills */
  .pill{display:inline-flex;align-items:center;padding:2px 8px;border-radius:99px;font-size:10.5px;font-weight:700;white-space:nowrap}
  .pill-green{background:#DCFCE7;color:#15803D}
  .pill-red{background:#FEE2E2;color:#DC2626}
  .pill-amber{background:#FEF3C7;color:#B45309}
  .pill-blue{background:#DBEAFE;color:#1D4ED8}
  .pill-slate{background:var(--slate1);color:var(--slate3)}
  .pill-teal{background:#CCFBF1;color:#0F766E}
  .pill-indigo{background:#EEF2FF;color:#4338CA}
  /* ── Buttons */
  .btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:var(--rs);border:none;cursor:pointer;font-size:12.5px;font-weight:600;transition:all .15s;font-family:inherit;white-space:nowrap}
  .btn:hover{opacity:.87;transform:translateY(-1px)}
  .btn:active{transform:translateY(0)}
  .btn-primary{background:var(--teal);color:#fff}
  .btn-secondary{background:var(--slate1);color:var(--slate8);border:1px solid var(--slate2)}
  .btn-indigo{background:var(--indigo);color:#fff}
  .btn-danger{background:#FEE2E2;color:var(--red)}
  .btn-sm{padding:5px 11px;font-size:11.5px}
  .btn:disabled{opacity:.4;cursor:not-allowed;transform:none}
  /* ── Alerts */
  .alert{border-radius:var(--rs);padding:11px 14px;font-size:12.5px;margin-bottom:14px;display:flex;gap:10px;align-items:flex-start;line-height:1.5}
  .alert-info{background:#EFF6FF;border:1px solid #BFDBFE;color:#1E40AF}
  .alert-warn{background:#FFFBEB;border:1px solid #FDE68A;color:#92400E}
  .alert-success{background:#F0FDF4;border:1px solid #BBF7D0;color:#15803D}
  .alert-error{background:#FEF2F2;border:1px solid #FECACA;color:#991B1B}
  /* ── Tabs */
  .tabs{display:flex;gap:2px;background:var(--slate1);border-radius:var(--rs);padding:3px;margin-bottom:18px;width:fit-content;flex-wrap:wrap}
  .tab{padding:7px 14px;border-radius:5px;font-size:12.5px;font-weight:500;cursor:pointer;color:var(--slate3);transition:all .15s;user-select:none}
  .tab.active{background:var(--white);color:var(--slate8);font-weight:700;box-shadow:var(--shadow)}
  /* ── Upload zone */
  .upload-zone{border:2px dashed var(--slate2);border-radius:var(--r);padding:28px;text-align:center;cursor:pointer;transition:all .2s}
  .upload-zone:hover{border-color:var(--teal);background:var(--teal-light)}
  /* ── Progress */
  .prog-bar{background:var(--slate1);border-radius:99px;height:5px;overflow:hidden;margin-top:6px}
  .prog-fill{height:100%;border-radius:99px;transition:width .5s}
  /* ── Forms */
  .form-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin-bottom:14px}
  .form-group{display:flex;flex-direction:column;gap:4px}
  label{font-size:11px;font-weight:600;color:var(--slate3);text-transform:uppercase;letter-spacing:.05em}
  input,select,textarea{padding:8px 11px;border:1px solid var(--slate2);border-radius:var(--rs);font-size:13px;color:var(--slate8);background:var(--white);outline:none;transition:border .15s;font-family:inherit;width:100%}
  input:focus,select:focus,textarea:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(0,184,169,.1)}
  /* ── Modal */
  .modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1000;display:flex;align-items:center;justify-content:center;padding:16px;backdrop-filter:blur(2px)}
  .modal{background:var(--white);border-radius:var(--r);box-shadow:var(--shadow-md);width:640px;max-width:100%;max-height:90vh;overflow-y:auto;animation:modalIn .2s ease}
  @keyframes modalIn{from{opacity:0;transform:scale(.97)}to{opacity:1;transform:scale(1)}}
  .modal-hd{padding:20px 24px;border-bottom:1px solid var(--slate1);display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;background:var(--white);z-index:1}
  .modal-hd h2{font-size:15px;font-weight:800}
  .modal-body{padding:24px}
  .modal-ft{padding:14px 24px;border-top:1px solid var(--slate1);display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap}
  .modal-close{background:none;border:none;cursor:pointer;font-size:18px;color:var(--slate3);padding:4px;line-height:1}
  /* ── AI Bubbles */
  .ai-bubble{background:linear-gradient(135deg,#EFF6FF,#F0FDFA);border:1px solid #BFDBFE;border-radius:var(--r);padding:14px 16px;font-size:13px;color:var(--slate8);margin-bottom:10px;line-height:1.6}
  .ai-bubble b{color:var(--indigo)}
  .user-bubble{background:var(--indigo);color:#fff;border-radius:var(--r);padding:10px 14px;max-width:78%;font-size:13px;line-height:1.5;align-self:flex-end}
  .ai-chip{display:inline-block;background:var(--slate1);border:1px solid var(--slate2);border-radius:99px;padding:4px 12px;font-size:11.5px;cursor:pointer;margin:3px;transition:all .15s;font-weight:500}
  .ai-chip:hover{background:var(--teal);color:#fff;border-color:var(--teal)}
  /* ── Spinner */
  .spinner{width:18px;height:18px;border:2px solid var(--slate1);border-top-color:var(--teal);border-radius:50%;animation:spin .65s linear infinite;flex-shrink:0}
  @keyframes spin{to{transform:rotate(360deg)}}
  /* ── Invoice */
  .inv-paper{background:var(--white);border:1px solid var(--slate1);border-radius:var(--r);padding:28px;max-width:680px;margin:0 auto}
  .inv-hd{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:20px;gap:16px}
  .inv-logo-name{font-size:19px;font-weight:900;color:var(--navy)}
  .inv-logo-tag{font-size:10px;color:var(--slate3);margin-top:2px}
  .inv-meta{text-align:right;font-size:11.5px;color:var(--slate3)}
  .inv-meta strong{color:var(--slate8)}
  .inv-divider{border:none;border-top:1px solid var(--slate1);margin:14px 0}
  /* ── Plan cards */
  .plan-card{background:var(--white);border-radius:var(--r);box-shadow:var(--shadow);padding:22px;border:2px solid var(--slate1);transition:all .2s;cursor:pointer}
  .plan-card:hover{border-color:var(--teal);box-shadow:var(--shadow-md)}
  .plan-card.featured{border-color:var(--teal);position:relative}
  .plan-card.featured::before{content:'Most Popular';position:absolute;top:-11px;left:50%;transform:translateX(-50%);background:var(--teal);color:#fff;font-size:10px;font-weight:700;padding:2px 12px;border-radius:99px;white-space:nowrap}
  .plan-price{font-size:26px;font-weight:900;color:var(--slate8);margin:10px 0 2px;letter-spacing:-.02em}
  .plan-price span{font-size:13px;font-weight:400;color:var(--slate3)}
  .plan-feat{display:flex;align-items:flex-start;gap:8px;font-size:12.5px;padding:4px 0}
  .plan-feat::before{content:'✓';color:var(--teal);font-weight:800;flex-shrink:0}
  /* ── Risk ring */
  .risk-ring{width:34px;height:34px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;flex-shrink:0}
  .risk-low{background:#DCFCE7;color:#15803D}
  .risk-med{background:#FEF3C7;color:#B45309}
  .risk-high{background:#FEE2E2;color:#DC2626}
  /* ── Deadline */
  .dl-row{display:flex;align-items:center;gap:12px;padding:10px 0;border-bottom:1px solid var(--slate1)}
  .dl-row:last-child{border-bottom:none}
  .dl-icon{width:36px;height:36px;border-radius:var(--rs);display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
  /* ── Scrollbar */
  ::-webkit-scrollbar{width:5px;height:5px}
  ::-webkit-scrollbar-track{background:transparent}
  ::-webkit-scrollbar-thumb{background:var(--slate2);border-radius:99px}
  /* ── Responsive */
  @media(max-width:768px){
    .sidebar{width:52px}
    .sb-logo-title,.sb-logo-sub,.sb-fy,.sb-section,.sb-badge{display:none}
    .sb-item span:not(.si){display:none}
    .sb-footer{display:none}
    .g4{grid-template-columns:repeat(2,1fr)}
    .g3{grid-template-columns:repeat(2,1fr)}
    .g2{grid-template-columns:1fr}
    .content{padding:14px}
  }
  @media(max-width:480px){
    .g4,.g3,.g2{grid-template-columns:1fr}
    .topbar{padding:0 14px}
  }
`;

// ── DATA ──────────────────────────────────────────────────────────────────────
const FYS = ["2025-26","2024-25","2023-24"];
const MONTHS_FY = ["Apr 2025","May 2025","Jun 2025","Jul 2025","Aug 2025","Sep 2025","Oct 2025","Nov 2025","Dec 2025","Jan 2026","Feb 2026","Mar 2026"];

const INVOICES = [
  {gstin:"27AABCU9603R1ZM",vendor:"Infosys Ltd",inv:"INF/2025/1234",dt:"05-Apr-25",taxable:485000,igst:87300,cgst:0,sgst:0,total:572300,status:"matched",itc:87300},
  {gstin:"29AABCU9603R1ZP",vendor:"TCS Limited",inv:"TCS/2025/5621",dt:"08-Apr-25",taxable:210000,igst:0,cgst:18900,sgst:18900,total:247800,status:"matched",itc:37800},
  {gstin:"06AABCU9603R1ZQ",vendor:"Wipro Ltd",inv:"WIP/25/889",dt:"12-Apr-25",taxable:95000,igst:17100,cgst:0,sgst:0,total:112100,status:"mismatch",itc:0},
  {gstin:"19AABCU9603R1ZR",vendor:"HCL Technologies",inv:"HCL/2025/4412",dt:"15-Apr-25",taxable:320000,igst:57600,cgst:0,sgst:0,total:377600,status:"missing",itc:0},
  {gstin:"07AABCU9603R1ZS",vendor:"Cognizant India",inv:"COG/2025/7733",dt:"18-Apr-25",taxable:175000,igst:0,cgst:15750,sgst:15750,total:206500,status:"matched",itc:31500},
  {gstin:"24AABCU9603R1ZT",vendor:"Tech Mahindra",inv:"TM/2025/3301",dt:"22-Apr-25",taxable:89000,igst:16020,cgst:0,sgst:0,total:105020,status:"duplicate",itc:0},
  {gstin:"27AABCU9603R1ZU",vendor:"Mphasis Ltd",inv:"MPH/25/2211",dt:"25-Apr-25",taxable:142000,igst:25560,cgst:0,sgst:0,total:167560,status:"matched",itc:25560},
  {gstin:"33AABCU9603R1ZV",vendor:"L&T Infotech",inv:"LTI/2025/9988",dt:"28-Apr-25",taxable:256000,igst:0,cgst:23040,sgst:23040,total:302080,status:"mismatch",itc:0},
  {gstin:"27AABCU9603R1ZW",vendor:"Hexaware Tech",inv:"HEX/25/4421",dt:"02-May-25",taxable:98000,igst:17640,cgst:0,sgst:0,total:115640,status:"matched",itc:17640},
  {gstin:"09AABCU9603R1ZX",vendor:"Zensar Technologies",inv:"ZEN/25/881",dt:"05-May-25",taxable:185000,igst:33300,cgst:0,sgst:0,total:218300,status:"matched",itc:33300},
];

const CLIENTS = [
  {name:"Sharma & Associates CA",gstin:"27AABCS1234A1ZN",type:"CA Firm",invoices:12400,plan:"Enterprise",status:"active",risk:"low"},
  {name:"Mehta Tax Consultants",gstin:"29AABCM4321B1ZP",type:"Tax Consultant",invoices:8900,plan:"Pro",status:"active",risk:"low"},
  {name:"Rajesh Enterprises Ltd",gstin:"06AABCR9876C1ZQ",type:"SME",invoices:4450,plan:"Starter",status:"active",risk:"med"},
  {name:"Global Finance Group",gstin:"19AABCG5432D1ZR",type:"Enterprise",invoices:32000,plan:"Enterprise",status:"active",risk:"low"},
  {name:"Patel & Co CA",gstin:"24AABCP7654E1ZS",type:"CA Firm",invoices:6700,plan:"Pro",status:"trial",risk:"med"},
  {name:"Jain Brothers Trading",gstin:"07AABCJ9012F1ZT",type:"SME",invoices:2100,plan:"Starter",status:"active",risk:"high"},
];

const DEADLINES = [
  {form:"GSTR-1",period:"May 2025",due:"11-Jun-25",days:0,status:"filed",penalty:"₹50/day max ₹10,000"},
  {form:"GSTR-3B",period:"May 2025",due:"20-Jun-25",days:4,status:"pending",penalty:"₹50/day + 18% interest"},
  {form:"GSTR-1",period:"Jun 2025",due:"11-Jul-25",days:25,status:"upcoming",penalty:"₹50/day max ₹10,000"},
  {form:"GSTR-3B",period:"Jun 2025",due:"20-Jul-25",days:34,status:"upcoming",penalty:"₹50/day + 18% interest"},
  {form:"GSTR-2B",period:"May 2025",due:"14-Jun-25",days:-2,status:"filed",penalty:"N/A — Auto generated"},
  {form:"GSTR-9",period:"FY 2024-25",due:"31-Dec-25",days:198,status:"upcoming",penalty:"₹200/day max 0.25% turnover"},
  {form:"GSTR-9C",period:"FY 2024-25",due:"31-Dec-25",days:198,status:"upcoming",penalty:"₹200/day max 0.25% turnover"},
];

const VENDORS = [
  {name:"Infosys Ltd",gstin:"27AABCU9603R1ZM",invoices:28,taxable:4850000,itc:873000,matched:100,filed:100,risk:"low"},
  {name:"TCS Limited",gstin:"29AABCU9603R1ZP",invoices:22,taxable:2100000,itc:378000,matched:100,filed:100,risk:"low"},
  {name:"Wipro Ltd",gstin:"06AABCU9603R1ZQ",invoices:15,taxable:950000,itc:171000,matched:87,filed:93,risk:"med"},
  {name:"HCL Technologies",gstin:"19AABCU9603R1ZR",invoices:19,taxable:3200000,itc:576000,matched:73,filed:78,risk:"high"},
  {name:"Cognizant India",gstin:"07AABCU9603R1ZS",invoices:11,taxable:1750000,itc:315000,matched:100,filed:100,risk:"low"},
  {name:"Tech Mahindra",gstin:"24AABCU9603R1ZT",invoices:9,taxable:890000,itc:160200,matched:89,filed:91,risk:"med"},
  {name:"Mphasis Ltd",gstin:"27AABCU9603R1ZU",invoices:14,taxable:1420000,itc:255600,matched:100,filed:100,risk:"low"},
  {name:"L&T Infotech",gstin:"33AABCU9603R1ZV",invoices:17,taxable:2560000,itc:460800,matched:82,filed:85,risk:"med"},
];

const PLANS = [
  {name:"Starter",price:999,joiningFee:1999,clients:10,invoices:"50,000",color:"slate",
   features:["Purchase & Sales Reconciliation","GSTR-2B Import","GSTR-1 Reconciliation","Missing ITC Report","Mismatch Detection","Excel & PDF Export","Vendor Summary","Compliance Calendar","Email Support","FY 2025-26 Ready"]},
  {name:"Pro",price:2499,joiningFee:4999,clients:50,invoices:"Unlimited",color:"teal",featured:true,
   features:["Everything in Starter","🤖 AI Mismatch Explanation","🤖 AI Compliance Assistant","GSTR-9 Annual Return Workings","Vendor Risk Scoring","Multi-GSTIN Support","Duplicate Detection","ITC Reversal Report (Rule 42/43)","White Label PDF Reports","Priority Support (24hr)","Audit Trail & Logs"]},
  {name:"Enterprise",price:7499,joiningFee:9999,clients:999,invoices:"Unlimited",color:"indigo",
   features:["Everything in Pro","Unlimited Clients","🤖 AI Audit Assistant","🤖 AI Tax Forecasting","Custom Approval Workflows","API Access","Branch Management","Dedicated Account Manager","White Labeling","SLA 99.9% Uptime","On-site Training"]},
];

// ── HELPERS ───────────────────────────────────────────────────────────────────
const inr = n => "₹" + Number(n).toLocaleString("en-IN");
const inrL = n => "₹" + (n/100000).toFixed(2) + "L";
const inrCr = n => "₹" + (n/10000000).toFixed(2) + " Cr";

function Pill({type,children}){
  const cls={green:"pill-green",red:"pill-red",amber:"pill-amber",blue:"pill-blue",slate:"pill-slate",teal:"pill-teal",indigo:"pill-indigo"};
  return React.createElement("span",{className:`pill ${cls[type]||"pill-slate"}`},children);
}

function StatusPill({s}){
  const map={matched:["green","✓ Matched"],mismatch:["amber","⚠ Mismatch"],missing:["red","✗ Missing"],duplicate:["blue","⊕ Duplicate"],filed:["green","✓ Filed"],pending:["amber","⏳ Pending"],upcoming:["slate","📅 Upcoming"],active:["green","Active"],trial:["amber","Trial"],low:["green","Low Risk"],med:["amber","Med Risk"],high:["red","High Risk"]};
  const [c,l]=map[s]||["slate",s];
  return React.createElement(Pill,{type:c},l);
}

function MiniBar({pct,color}){
  return React.createElement("div",{className:"prog-bar"},
    React.createElement("div",{className:"prog-fill",style:{width:Math.min(pct,100)+"%",background:color||"var(--teal)"}})
  );
}

function Btn({cls="btn-secondary",sm,onClick,disabled,children}){
  return React.createElement("button",{className:`btn ${cls} ${sm?"btn-sm":""}`,onClick,disabled},children);
}

// ── DASHBOARD ─────────────────────────────────────────────────────────────────
function Dashboard({onNav}){
  const stats=[
    {label:"Total Invoices Processed",val:"1,28,470",sub:"FY 2025-26 · Unlimited",delta:"↑ 18.3% vs last FY",up:true,c:"c-teal"},
    {label:"ITC Claimed",val:"₹4.82 Cr",sub:"GSTR-2B matched & verified",delta:"↑ 12.1%",up:true,c:"c-indigo"},
    {label:"Mismatches Found",val:"234",sub:"Pending resolution",delta:"↓ 8.4% vs last month",up:false,c:"c-amber"},
    {label:"Missing ITC",val:"₹18.4 L",sub:"Not reflected in GSTR-2B",delta:"Action required",up:false,c:"c-red"},
  ];
  const monthly=[
    {m:"Apr 25",matched:95,mm:3,miss:2,total:14200},
    {m:"May 25",matched:97,mm:2,miss:1,total:12800},
    {m:"Jun 25",matched:91,mm:6,miss:3,total:15600},
    {m:"Jul 25",matched:94,mm:4,miss:2,total:11900},
    {m:"Aug 25",matched:89,mm:7,miss:4,total:13400},
  ];
  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"GST Reconciliation Dashboard"),
      React.createElement("p",null,`FY ${CONFIG.FY} · Real-time compliance overview · Powered by AI · by ${CONFIG.COMPANY}`)
    ),
    React.createElement("div",{className:"alert alert-warn"},
      "⚠️ ",React.createElement("span",null,
        React.createElement("b",null,"GSTR-3B for May 2025"),
        " due ",React.createElement("b",null,"20-Jun-2025")," — 4 days remaining. Late fee: ₹50/day + 18% interest on tax. ",
        React.createElement("span",{style:{color:"var(--teal)",cursor:"pointer",fontWeight:700},onClick:()=>onNav("compliance")},"View Compliance Calendar →")
      )
    ),
    React.createElement("div",{className:"g4"},
      stats.map(s=>React.createElement("div",{key:s.label,className:`stat-card ${s.c}`},
        React.createElement("div",{className:"stat-lbl"},s.label),
        React.createElement("div",{className:"stat-val"},s.val),
        React.createElement("div",{className:"stat-sub"},s.sub),
        React.createElement("div",{className:`stat-delta ${s.up?"delta-up":"delta-dn"}`},s.delta)
      ))
    ),
    React.createElement("div",{className:"g2"},
      React.createElement("div",{className:"card"},
        React.createElement("div",{className:"card-hd"},
          React.createElement("h3",null,"Monthly Match Rate — FY 2025-26"),
          React.createElement("span",{className:"card-link",onClick:()=>onNav("reconcile")},"Run Reconciliation →")
        ),
        monthly.map(r=>React.createElement("div",{key:r.m,style:{marginBottom:12}},
          React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4}},
            React.createElement("span",{style:{fontSize:12,fontWeight:600}},r.m),
            React.createElement("span",{style:{fontSize:11,color:"var(--slate3)"}},r.total.toLocaleString("en-IN")," invoices · ",
              React.createElement("b",{style:{color:"var(--teal)"}},r.matched,"% matched")
            )
          ),
          React.createElement("div",{style:{display:"flex",gap:2,height:8,borderRadius:4,overflow:"hidden"}},
            React.createElement("div",{style:{flex:r.matched,background:"var(--green)"}}),
            React.createElement("div",{style:{flex:r.mm,background:"var(--amber)"}}),
            React.createElement("div",{style:{flex:r.miss,background:"var(--red)"}})
          )
        )),
        React.createElement("div",{style:{display:"flex",gap:16,marginTop:10,fontSize:11,color:"var(--slate3)"}},
          React.createElement("span",null,"🟢 Matched"),
          React.createElement("span",null,"🟡 Mismatch"),
          React.createElement("span",null,"🔴 Missing")
        )
      ),
      React.createElement("div",{className:"card"},
        React.createElement("div",{className:"card-hd"},
          React.createElement("h3",null,"Compliance Deadlines"),
          React.createElement("span",{className:"card-link",onClick:()=>onNav("compliance")},"All Deadlines →")
        ),
        DEADLINES.slice(0,5).map(d=>React.createElement("div",{key:d.form+d.period,className:"dl-row"},
          React.createElement("div",{className:"dl-icon",style:{background:d.status==="filed"?"#DCFCE7":d.status==="pending"?"#FEF3C7":"var(--slate1)"}},
            d.status==="filed"?"✅":d.status==="pending"?"⏳":"📅"
          ),
          React.createElement("div",{style:{flex:1}},
            React.createElement("div",{style:{fontWeight:600,fontSize:12.5}},d.form," — ",d.period),
            React.createElement("div",{style:{fontSize:11,color:"var(--slate3)"}},"Due: ",d.due)
          ),
          React.createElement(StatusPill,{s:d.status})
        ))
      )
    ),
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"Recent Invoices — Reconciliation Status"),
        React.createElement("div",{style:{display:"flex",gap:8}},
          React.createElement(Btn,{sm:true,onClick:()=>onNav("reconcile")},"View All"),
          React.createElement(Btn,{cls:"btn-primary",sm:true,onClick:()=>onNav("ai")},"🤖 AI Analyse")
        )
      ),
      React.createElement("div",{className:"tbl-wrap"},
        React.createElement("table",null,
          React.createElement("thead",null,React.createElement("tr",null,
            ["GSTIN","Vendor","Invoice No.","Date","Taxable (₹)","Tax (₹)","Total (₹)","Status"].map(h=>React.createElement("th",{key:h},h))
          )),
          React.createElement("tbody",null,
            INVOICES.slice(0,6).map(r=>React.createElement("tr",{key:r.inv},
              React.createElement("td",{className:"mono"},r.gstin),
              React.createElement("td",{style:{fontWeight:600}},r.vendor),
              React.createElement("td",{className:"mono"},r.inv),
              React.createElement("td",null,r.dt),
              React.createElement("td",{className:"mono"},r.taxable.toLocaleString("en-IN")),
              React.createElement("td",{className:"mono"},(r.igst||r.cgst+r.sgst).toLocaleString("en-IN")),
              React.createElement("td",{className:"mono",style:{fontWeight:700}},r.total.toLocaleString("en-IN")),
              React.createElement("td",null,React.createElement(StatusPill,{s:r.status}))
            ))
          )
        )
      )
    )
  );
}

// ── IMPORT DATA ───────────────────────────────────────────────────────────────
function ImportData(){
  const [uploaded,setUploaded]=useState([]);
  const [progress,setProgress]=useState({});

  const fileTypes=[
    {id:"pr",icon:"🗂️",title:"Purchase Register",desc:"Upload purchase register — Excel (.xlsx) or CSV. No row limit.",tag:"Required",color:"var(--red)"},
    {id:"sr",icon:"📊",title:"Sales Register",desc:"Upload sales register — Excel (.xlsx) or CSV. Unlimited rows.",tag:"Required",color:"var(--red)"},
    {id:"g2b",icon:"📥",title:"GSTR-2B",desc:"Download JSON or Excel from GST Portal and import here.",tag:"Required",color:"var(--red)"},
    {id:"g1",icon:"📤",title:"GSTR-1",desc:"Import filed GSTR-1 for sales reconciliation.",tag:"Optional",color:"var(--slate3)"},
    {id:"g3b",icon:"📋",title:"GSTR-3B",desc:"Import to compare ITC claimed vs available.",tag:"Optional",color:"var(--slate3)"},
    {id:"g9",icon:"📑",title:"GSTR-9 / 9C",desc:"Import for annual reconciliation workings.",tag:"Optional",color:"var(--slate3)"},
  ];

  const handleUpload=useCallback((id)=>{
    setProgress(p=>({...p,[id]:0}));
    let pct=0;
    const iv=setInterval(()=>{
      pct+=Math.random()*25+10;
      if(pct>=100){pct=100;clearInterval(iv);setUploaded(u=>[...new Set([...u,id])]);setProgress(p=>({...p,[id]:100}));}
      setProgress(p=>({...p,[id]:Math.min(pct,100)}));
    },300);
  },[]);

  const uploaded3=uploaded.length>=3;

  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Import Data"),
      React.createElement("p",null,"Upload your GST data — no invoice limits, FY 2025-26 supported. Supports Excel, CSV, JSON.")
    ),
    React.createElement("div",{className:"alert alert-info"},
      "ℹ️ ",React.createElement("span",null,"Supported formats: Excel (.xlsx/.xls), CSV, JSON (GST Portal export). ",React.createElement("b",null,"No row/invoice limit.")," All data validated against GST Rules 2026 before reconciliation.")
    ),
    React.createElement("div",{className:"g3"},
      fileTypes.map(f=>React.createElement("div",{key:f.id,className:"card",style:{border:uploaded.includes(f.id)?"1.5px solid var(--teal)":"1.5px solid var(--slate1)",transition:"all .2s"}},
        React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:10}},
          React.createElement("span",{style:{fontSize:26}},f.icon),
          React.createElement(Pill,{type:f.tag==="Required"?"red":"slate"},f.tag)
        ),
        React.createElement("div",{style:{fontWeight:700,marginBottom:4,fontSize:13}},f.title),
        React.createElement("div",{style:{fontSize:11.5,color:"var(--slate3)",marginBottom:14}},f.desc),
        progress[f.id]!==undefined && progress[f.id]<100
          ? React.createElement("div",null,
              React.createElement("div",{style:{fontSize:11,color:"var(--teal)",marginBottom:4}},"Uploading & Validating..."),
              React.createElement(MiniBar,{pct:progress[f.id]})
            )
          : uploaded.includes(f.id)
            ? React.createElement("div",{className:"alert alert-success",style:{marginBottom:0,padding:"8px 12px"}},"✓ Uploaded & Validated")
            : React.createElement(Btn,{cls:"btn-primary",onClick:()=>handleUpload(f.id)},"📎 Upload File")
      ))
    ),
    uploaded3 && React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},React.createElement("h3",null,"Validation Summary")),
      React.createElement("div",{className:"g4"},
        [["Total Records","1,28,470","✅"],["Valid Records","1,27,813","✅"],["Duplicate GSTINs","182","⚠️"],["Invalid Invoice Nos","210","⚠️"]].map(([l,v,ic])=>
          React.createElement("div",{key:l,style:{textAlign:"center"}},
            React.createElement("div",{style:{fontSize:26,marginBottom:6}},ic),
            React.createElement("div",{style:{fontSize:20,fontWeight:800}},v),
            React.createElement("div",{style:{fontSize:11,color:"var(--slate3)"}},l)
          )
        )
      ),
      React.createElement("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginTop:12}},
        React.createElement(Btn,null,"📥 Download Validation Report"),
        React.createElement(Btn,{cls:"btn-primary"},"▶ Start Reconciliation")
      )
    )
  );
}

// ── RECONCILIATION ────────────────────────────────────────────────────────────
function Reconciliation(){
  const [tab,setTab]=useState("2b");
  const [filter,setFilter]=useState("all");
  const counts={all:INVOICES.length,matched:INVOICES.filter(r=>r.status==="matched").length,mismatch:INVOICES.filter(r=>r.status==="mismatch").length,missing:INVOICES.filter(r=>r.status==="missing").length,duplicate:INVOICES.filter(r=>r.status==="duplicate").length};
  const filtered=filter==="all"?INVOICES:INVOICES.filter(r=>r.status===filter);

  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Reconciliation Centre"),
      React.createElement("p",null,"AI-powered invoice matching — GSTR-2B vs Purchase Register. FY 2025-26. Unlimited invoices.")
    ),
    React.createElement("div",{className:"tabs"},
      [["2b","Purchase Reg vs GSTR-2B"],["g1","GSTR-1 vs Sales Reg"],["vendor","Vendor-wise"],["month","Month-wise"],["einv","E-Invoice Match"]].map(([k,l])=>
        React.createElement("div",{key:k,className:`tab ${tab===k?"active":""}`,onClick:()=>setTab(k)},l)
      )
    ),
    React.createElement("div",{className:"g4",style:{marginBottom:14}},
      [["All","all","var(--teal)"],["✓ Matched","matched","var(--green)"],["⚠ Mismatch","mismatch","var(--amber)"],["✗ Missing","missing","var(--red)"]].map(([l,k,c])=>
        React.createElement("div",{key:k,className:"stat-card c-teal",
          style:{cursor:"pointer",border:filter===k?"2px solid var(--teal)":"2px solid transparent",transition:"all .15s"},
          onClick:()=>setFilter(k)},
          React.createElement("div",{className:"stat-lbl"},l),
          React.createElement("div",{className:"stat-val"},counts[k]),
          React.createElement(MiniBar,{pct:(counts[k]/counts.all)*100,color:c})
        )
      )
    ),
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"Invoice-level Reconciliation — ",MONTHS_FY[1]),
        React.createElement("div",{style:{display:"flex",gap:8,flexWrap:"wrap"}},
          React.createElement(Btn,{sm:true},"📊 Export Excel"),
          React.createElement(Btn,{sm:true},"📄 Export PDF"),
          React.createElement(Btn,{cls:"btn-primary btn-sm",sm:true},"🤖 AI Explain All Mismatches")
        )
      ),
      React.createElement("div",{className:"tbl-wrap"},
        React.createElement("table",null,
          React.createElement("thead",null,React.createElement("tr",null,
            ["GSTIN","Vendor","Invoice No.","Date","Taxable","IGST","CGST","SGST","Total","ITC Eligible","Status","Action"].map(h=>React.createElement("th",{key:h},h))
          )),
          React.createElement("tbody",null,
            filtered.map(r=>React.createElement("tr",{key:r.inv},
              React.createElement("td",{className:"mono",style:{fontSize:10.5}},r.gstin),
              React.createElement("td",{style:{fontWeight:600}},r.vendor),
              React.createElement("td",{className:"mono"},r.inv),
              React.createElement("td",null,r.dt),
              React.createElement("td",{className:"mono"},r.taxable.toLocaleString("en-IN")),
              React.createElement("td",{className:"mono"},r.igst||"—"),
              React.createElement("td",{className:"mono"},r.cgst||"—"),
              React.createElement("td",{className:"mono"},r.sgst||"—"),
              React.createElement("td",{className:"mono",style:{fontWeight:700}},r.total.toLocaleString("en-IN")),
              React.createElement("td",{className:"mono",style:{color:r.itc>0?"var(--green)":"var(--red)",fontWeight:700}},r.itc>0?r.itc.toLocaleString("en-IN"):"₹0"),
              React.createElement("td",null,React.createElement(StatusPill,{s:r.status})),
              React.createElement("td",null,React.createElement(Btn,{sm:true},"View"))
            ))
          )
        )
      )
    )
  );
}

// ── AI ASSISTANT ──────────────────────────────────────────────────────────────
function AIAssistant(){
  const [messages,setMessages]=useState([
    {role:"ai",text:"Hello! I'm your AI GST Compliance Assistant, powered by Claude AI.\n\nI can help you:\n• Explain reconciliation mismatches in plain language\n• Calculate maximum ITC claimable under Section 16\n• Identify vendor GSTIN compliance issues\n• Draft replies to GST notices & queries\n• Explain GST Rules 2026 changes\n• Optimize your ITC claim strategy\n\nWhat would you like to know about your GST data?"}
  ]);
  const [input,setInput]=useState("");
  const [loading,setLoading]=useState(false);
  const bottomRef=useRef(null);

  const suggestions=[
    "Explain the mismatches in my data","Why is ITC being blocked in GSTR-2B?","What is Section 16(4) ITC deadline for FY 2025-26?","How to handle a GST mismatch notice?","Calculate Rule 42 ITC reversal","Which vendors have compliance issues?","What changed in GST Rules 2026?","How to claim missing ITC from supplier?","Explain GSTR-9 vs GSTR-9C difference","What is E-Invoice mandate 2025?",
  ];

  const callAI=useCallback(async(q)=>{
    if(!q.trim()||loading)return;
    const userMsg={role:"user",text:q};
    setMessages(p=>[...p,userMsg]);
    setInput("");
    setLoading(true);
    try{
      const history=messages.filter((_,i)=>i>0).map(m=>({role:m.role==="ai"?"assistant":"user",content:m.text}));
      const res=await fetch(CONFIG.AI_ENDPOINT,{
        method:"POST",
        headers:{"Content-Type":"application/json","x-api-key":CONFIG.AI_KEY,"anthropic-version":"2023-06-01"},
        body:JSON.stringify({
          model:"claude-sonnet-4-6",
          max_tokens:1000,
          system:`You are an expert AI GST Compliance Assistant for ProfitPulse GST Pro, developed by Vatsa Traders.

You have deep expertise in:
- GST Act 2017 and all amendments including GST Rules 2026
- GSTR-1, GSTR-2B, GSTR-3B, GSTR-9, GSTR-9C filing procedures
- ITC eligibility under Sections 16, 17, 18 of CGST Act
- GSTR-2B auto-draft vs purchase register reconciliation
- Section 16(2)(aa) — ITC only as per GSTR-2B from FY 2025-26
- Section 16(4) — ITC claim deadline (30 Nov of following FY)
- Rule 42 & 43 — ITC reversal for mixed/exempt supplies
- Rule 86B — restriction on ITC utilization for tax payment
- E-Invoice mandate (B2B transactions, all turnover levels from 2025)
- HSN code requirements (6-digit for >₹5Cr turnover, 4-digit others)
- GSTIN validation and vendor compliance monitoring
- Late fee structure, interest calculation, penalty provisions
- Recent GST Council decisions up to 2026

Current user context: FY 2025-26 | 1,28,470 invoices | ₹4.82 Cr ITC | 234 mismatches | ₹18.4L missing ITC
Platform: ProfitPulse GST Pro by Vatsa Traders

Be specific, cite provisions, give actionable advice. Keep responses clear and structured.`,
          messages:[...history,{role:"user",content:q}]
        })
      });
      const data=await res.json();
      const reply=data.content?.map(c=>c.text||"").join("")||"Sorry, I couldn't process that. Please check your API configuration.";
      setMessages(p=>[...p,{role:"ai",text:reply}]);
    }catch(e){
      setMessages(p=>[...p,{role:"ai",text:"Connection error. Please ensure your Anthropic API key is configured in CONFIG.AI_KEY and try again."}]);
    }
    setLoading(false);
  },[messages,loading]);

  useEffect(()=>{bottomRef.current?.scrollIntoView({behavior:"smooth"})},[messages,loading]);

  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"🤖 AI GST Compliance Assistant"),
      React.createElement("p",null,"Powered by Claude AI · Ask anything about GST reconciliation, ITC, notices, or compliance")
    ),
    React.createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 270px",gap:16}},
      React.createElement("div",{className:"card",style:{display:"flex",flexDirection:"column",height:560}},
        React.createElement("div",{style:{flex:1,overflowY:"auto",display:"flex",flexDirection:"column",gap:4,paddingBottom:8}},
          messages.map((m,i)=>
            m.role==="ai"
              ? React.createElement("div",{key:i,className:"ai-bubble"},
                  React.createElement("b",null,"🤖 ProfitPulse AI"),React.createElement("br",null),React.createElement("br",null),
                  React.createElement("span",{style:{whiteSpace:"pre-wrap"}},m.text)
                )
              : React.createElement("div",{key:i,style:{display:"flex",justifyContent:"flex-end"}},
                  React.createElement("div",{className:"user-bubble"},m.text)
                )
          ),
          loading && React.createElement("div",{className:"ai-bubble"},
            React.createElement("b",null,"🤖 ProfitPulse AI"),React.createElement("br",null),React.createElement("br",null),
            React.createElement("div",{style:{display:"flex",gap:8,alignItems:"center"}},
              React.createElement("div",{className:"spinner"}),
              React.createElement("span",{style:{color:"var(--slate3)"}},  "Analysing your GST data...")
            )
          ),
          React.createElement("div",{ref:bottomRef})
        ),
        React.createElement("div",{style:{borderTop:"1px solid var(--slate1)",paddingTop:12,display:"flex",gap:8}},
          React.createElement("input",{value:input,onChange:e=>setInput(e.target.value),onKeyDown:e=>e.key==="Enter"&&!e.shiftKey&&callAI(input),placeholder:"Ask about GST reconciliation, ITC, notices, compliance..."}),
          React.createElement(Btn,{cls:"btn-primary",onClick:()=>callAI(input),disabled:loading||!input.trim()},"Send")
        )
      ),
      React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:12}},
        React.createElement("div",{className:"card"},
          React.createElement("div",{className:"card-hd"},React.createElement("h3",null,"Quick Questions")),
          suggestions.map(s=>React.createElement("div",{key:s,className:"ai-chip",onClick:()=>callAI(s)},s))
        ),
        React.createElement("div",{className:"card"},
          React.createElement("div",{className:"card-hd"},React.createElement("h3",null,"AI Capabilities")),
          ["Mismatch Explanation","ITC Optimization","Vendor Risk Analysis","GST Notice Drafting","Rule 42/43 Reversal","Section 16(4) Deadline","GSTR-9 Workings","Tax Forecasting"].map(c=>
            React.createElement("div",{key:c,style:{display:"flex",gap:8,alignItems:"center",padding:"4px 0",fontSize:12.5}},
              React.createElement("span",{style:{color:"var(--teal)",fontWeight:700}},"✓"),c
            )
          )
        )
      )
    )
  );
}

// ── REPORTS ───────────────────────────────────────────────────────────────────
function Reports(){
  const reports=[
    {icon:"📊",title:"Mismatch Report",desc:"Invoice-level mismatch analysis with AI-powered explanations and resolution steps",tag:"Core"},
    {icon:"💰",title:"Missing ITC Report",desc:"ITC available in GSTR-2B but not claimed in purchase register",tag:"Core"},
    {icon:"🏢",title:"Vendor Summary",desc:"Vendor-wise ITC, match rate, compliance score and risk rating",tag:"Core"},
    {icon:"📋",title:"GST Summary Dashboard",desc:"Month-wise GST liability, ITC claimed, ITC available, and net payable",tag:"Core"},
    {icon:"🔍",title:"GSTR-2B vs 2A Comparison",desc:"Compare auto-drafted ITC (2B) with supplier-filed data (2A)",tag:"Advanced"},
    {icon:"📑",title:"GSTR-9 Annual Workings",desc:"Pre-fill annual return data from reconciled FY records",tag:"Advanced"},
    {icon:"⚖️",title:"ITC Reversal Report",desc:"Rule 42 & 43 reversal calculation for mixed and exempt supplies",tag:"Advanced"},
    {icon:"🌐",title:"HSN Summary Report",desc:"HSN/SAC-wise outward supply summary for GSTR-1 Table 12",tag:"Advanced"},
    {icon:"🎯",title:"E-Invoice Reconciliation",desc:"Match e-invoices from IRP with GSTR-1 auto-population data",tag:"Advanced"},
    {icon:"📉",title:"ITC Utilisation Report",desc:"IGST→CGST/SGST utilisation order per Section 49 — optimised",tag:"Advanced"},
    {icon:"🚨",title:"AI Audit Risk Report",desc:"AI-powered risk flags for GST department scrutiny & audit preparedness",tag:"AI"},
    {icon:"🤖",title:"AI Tax Insights",desc:"Smart AI recommendations to optimise ITC and reduce GST liability",tag:"AI"},
  ];
  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Reports & Analytics"),
      React.createElement("p",null,"Generate detailed GST reconciliation, compliance and AI-driven insight reports")
    ),
    React.createElement("div",{style:{display:"flex",gap:8,marginBottom:18,flexWrap:"wrap"}},
      React.createElement("select",{style:{width:"auto"}},FYS.map(f=>React.createElement("option",{key:f},f))),
      React.createElement("select",{style:{width:"auto"}},["All Months",...MONTHS_FY].map(m=>React.createElement("option",{key:m},m))),
      React.createElement("select",{style:{width:"auto"}},[React.createElement("option",{key:"all"},"All GSTINs")])
    ),
    React.createElement("div",{className:"g3"},
      reports.map(r=>React.createElement("div",{key:r.title,className:"card",style:{cursor:"pointer",transition:"box-shadow .15s"},
        onMouseEnter:e=>e.currentTarget.style.boxShadow="var(--shadow-md)",
        onMouseLeave:e=>e.currentTarget.style.boxShadow="var(--shadow)"},
        React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:10}},
          React.createElement("span",{style:{fontSize:26}},r.icon),
          React.createElement(Pill,{type:r.tag==="AI"?"teal":r.tag==="Advanced"?"blue":"slate"},r.tag)
        ),
        React.createElement("div",{style:{fontWeight:700,marginBottom:4,fontSize:13}},r.title),
        React.createElement("div",{style:{fontSize:11.5,color:"var(--slate3)",marginBottom:14}},r.desc),
        React.createElement("div",{style:{display:"flex",gap:8}},
          React.createElement(Btn,{sm:true},"📄 PDF"),
          React.createElement(Btn,{sm:true},"📊 Excel"),
          React.createElement(Btn,{cls:"btn-primary btn-sm",sm:true},"Generate")
        )
      ))
    )
  );
}

// ── COMPLIANCE CALENDAR ───────────────────────────────────────────────────────
function Compliance(){
  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Compliance Calendar"),
      React.createElement("p",null,"All GST filing deadlines, penalties, and GST Rules 2026 changes — FY 2025-26")
    ),
    React.createElement("div",{className:"alert alert-warn"},
      "⚠️ ",React.createElement("b",null,"GSTR-3B (May 2025)")," due 20-Jun-2025 — 4 days remaining. Late fee ₹50/day + 18% interest on outstanding tax. File immediately."
    ),
    React.createElement("div",{className:"g4"},
      [["Filed","4","✅"],["Due Soon","2","⏳"],["Upcoming","3","📅"],["Late FY26","0","🎉"]].map(([l,v,ic])=>
        React.createElement("div",{key:l,className:"stat-card c-teal"},
          React.createElement("div",{style:{fontSize:24,marginBottom:4}},ic),
          React.createElement("div",{className:"stat-val"},v),
          React.createElement("div",{className:"stat-lbl"},l)
        )
      )
    ),
    React.createElement("div",{className:"card",style:{marginBottom:16}},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"GST Return Filing Schedule — FY 2025-26"),
        React.createElement(Btn,{sm:true,cls:"btn-primary"},"📅 Add to Calendar")
      ),
      React.createElement("div",{className:"tbl-wrap"},
        React.createElement("table",null,
          React.createElement("thead",null,React.createElement("tr",null,
            ["Form","Applicable To","Frequency","Due Date","Late Fee / Penalty","Status"].map(h=>React.createElement("th",{key:h},h))
          )),
          React.createElement("tbody",null,
            DEADLINES.map(d=>React.createElement("tr",{key:d.form+d.period},
              React.createElement("td",{style:{fontWeight:800,color:"var(--indigo)"}},d.form),
              React.createElement("td",null,d.period),
              React.createElement("td",null,d.form.includes("9")?"Annual":"Monthly"),
              React.createElement("td",{style:{fontWeight:700}},d.due,d.days>0&&React.createElement("span",{style:{fontSize:10,color:"var(--amber)",marginLeft:6}},"({d.days} days left)")),
              React.createElement("td",{style:{color:"var(--red)",fontSize:11.5}},d.penalty),
              React.createElement("td",null,React.createElement(StatusPill,{s:d.status}))
            ))
          )
        )
      )
    ),
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},React.createElement("h3",null,"Critical GST Rule Changes — 2026")),
      [
        ["🔴","GSTR-2B Mandatory ITC Lock","Section 16(2)(aa) — ITC can only be claimed as appearing in GSTR-2B. No more 2A-based claims from FY 2025-26 onwards. ProfitPulse auto-enforces this."],
        ["🔴","E-Invoice Mandate — All B2B","E-Invoicing mandatory for all B2B transactions regardless of turnover from 2025. IRN must be embedded in GSTR-1."],
        ["⚠️","Section 16(4) Deadline","ITC for FY 2024-25 must be claimed by 30-Nov-2025 GSTR-3B. After this date, ITC is permanently lost."],
        ["⚠️","Rule 86B Cash Payment","If taxable turnover > ₹50 Lakh, minimum 1% of tax liability must be paid in cash (not ITC). Verify before filing."],
        ["ℹ️","HSN 6-Digit Mandate","6-digit HSN mandatory in GSTR-1 for turnover > ₹5 Cr. 4-digit for others. ProfitPulse validates automatically."],
        ["ℹ️","QR Code on Invoices","Dynamic QR code mandatory for B2C transactions for turnover > ₹500 Cr. Verify with e-invoice portal."],
      ].map(([badge,title,desc])=>
        React.createElement("div",{key:title,style:{display:"flex",gap:12,padding:"10px 0",borderBottom:"1px solid var(--slate1)"}},
          React.createElement("div",{style:{fontSize:18,flexShrink:0,marginTop:2}},badge),
          React.createElement("div",null,
            React.createElement("div",{style:{fontWeight:700,fontSize:13}},title),
            React.createElement("div",{style:{fontSize:11.5,color:"var(--slate3)",marginTop:2}},desc)
          )
        )
      )
    )
  );
}

// ── VENDOR ANALYSIS ───────────────────────────────────────────────────────────
function VendorAnalysis(){
  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Vendor Analysis & Risk Scoring"),
      React.createElement("p",null,"AI-powered vendor compliance monitoring, ITC risk assessment, and GSTIN health check")
    ),
    React.createElement("div",{className:"g4"},
      [["Total Vendors","8","🏢"],["High Risk","1","🔴"],["ITC at Risk","₹57.6L","⚠️"],["Avg Match Rate","93.9%","📊"]].map(([l,v,ic])=>
        React.createElement("div",{key:l,className:"stat-card c-teal"},
          React.createElement("div",{style:{fontSize:22,marginBottom:4}},ic),
          React.createElement("div",{className:"stat-val"},v),
          React.createElement("div",{className:"stat-lbl"},l)
        )
      )
    ),
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"Vendor Compliance Dashboard"),
        React.createElement(Btn,{cls:"btn-primary btn-sm",sm:true},"🤖 AI Risk Analysis All Vendors")
      ),
      React.createElement("div",{className:"tbl-wrap"},
        React.createElement("table",null,
          React.createElement("thead",null,React.createElement("tr",null,
            ["Vendor","GSTIN","Invoices","Taxable (₹)","ITC (₹)","Match Rate","GSTR Filing","Risk","Action"].map(h=>React.createElement("th",{key:h},h))
          )),
          React.createElement("tbody",null,
            VENDORS.map(v=>React.createElement("tr",{key:v.gstin},
              React.createElement("td",{style:{fontWeight:700}},v.name),
              React.createElement("td",{className:"mono",style:{fontSize:10.5}},v.gstin),
              React.createElement("td",{className:"mono"},v.invoices),
              React.createElement("td",{className:"mono"},(v.taxable/100000).toFixed(1),"L"),
              React.createElement("td",{className:"mono"},(v.itc/100000).toFixed(1),"L"),
              React.createElement("td",null,
                React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},
                  React.createElement("div",{style:{width:55,height:5,background:"var(--slate1)",borderRadius:99,overflow:"hidden"}},
                    React.createElement("div",{style:{width:v.matched+"%",height:"100%",background:v.matched===100?"var(--green)":v.matched>85?"var(--amber)":"var(--red)"}})
                  ),
                  React.createElement("span",{style:{fontSize:11.5,fontWeight:700}},v.matched,"%")
                )
              ),
              React.createElement("td",null,
                React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},
                  React.createElement("div",{style:{width:55,height:5,background:"var(--slate1)",borderRadius:99,overflow:"hidden"}},
                    React.createElement("div",{style:{width:v.filed+"%",height:"100%",background:v.filed===100?"var(--green)":v.filed>85?"var(--amber)":"var(--red)"}})
                  ),
                  React.createElement("span",{style:{fontSize:11.5,fontWeight:700}},v.filed,"%")
                )
              ),
              React.createElement("td",null,
                React.createElement("div",{className:`risk-ring risk-${v.risk}`},
                  v.risk==="low"?"✓":v.risk==="med"?"!":"✗"
                )
              ),
              React.createElement("td",null,React.createElement(Btn,{sm:true},"Details"))
            ))
          )
        )
      )
    )
  );
}

// ── CLIENTS ───────────────────────────────────────────────────────────────────
function Clients(){
  const [showAdd,setShowAdd]=useState(false);
  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Client Management"),
      React.createElement("p",null,"Manage all clients, GSTINs, and CA firm portfolios — multi-client support")
    ),
    React.createElement("div",{className:"g4"},
      [["Total Clients","47","🏢"],["Active","43","✅"],["Trial","4","⏳"],["GSTINs","128","🔑"]].map(([l,v,ic])=>
        React.createElement("div",{key:l,className:"stat-card c-teal"},
          React.createElement("div",{style:{fontSize:22,marginBottom:4}},ic),
          React.createElement("div",{className:"stat-val"},v),
          React.createElement("div",{className:"stat-lbl"},l)
        )
      )
    ),
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"Client Portfolio"),
        React.createElement(Btn,{cls:"btn-primary",onClick:()=>setShowAdd(true)},"+ Add Client")
      ),
      React.createElement("div",{className:"tbl-wrap"},
        React.createElement("table",null,
          React.createElement("thead",null,React.createElement("tr",null,
            ["Client Name","GSTIN","Type","Invoices FY26","Plan","Risk","Status","Actions"].map(h=>React.createElement("th",{key:h},h))
          )),
          React.createElement("tbody",null,
            CLIENTS.map(c=>React.createElement("tr",{key:c.gstin},
              React.createElement("td",{style:{fontWeight:700}},c.name),
              React.createElement("td",{className:"mono",style:{fontSize:10.5}},c.gstin),
              React.createElement("td",null,React.createElement(Pill,{type:"blue"},c.type)),
              React.createElement("td",{className:"mono"},c.invoices.toLocaleString("en-IN")),
              React.createElement("td",null,React.createElement(Pill,{type:c.plan==="Enterprise"?"teal":c.plan==="Pro"?"blue":"slate"},c.plan)),
              React.createElement("td",null,React.createElement(StatusPill,{s:c.risk})),
              React.createElement("td",null,React.createElement(StatusPill,{s:c.status})),
              React.createElement("td",null,
                React.createElement("div",{style:{display:"flex",gap:4}},
                  React.createElement(Btn,{sm:true},"View"),
                  React.createElement(Btn,{sm:true,cls:"btn-primary btn-sm"},"Reconcile")
                )
              )
            ))
          )
        )
      )
    ),
    showAdd && React.createElement("div",{className:"modal-overlay",onClick:()=>setShowAdd(false)},
      React.createElement("div",{className:"modal",onClick:e=>e.stopPropagation()},
        React.createElement("div",{className:"modal-hd"},
          React.createElement("h2",null,"Add New Client"),
          React.createElement("button",{className:"modal-close",onClick:()=>setShowAdd(false)},"✕")
        ),
        React.createElement("div",{className:"modal-body"},
          React.createElement("div",{className:"form-row"},
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"Business Name *"),React.createElement("input",{placeholder:"e.g. Sharma & Associates CA"})),
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"GSTIN *"),React.createElement("input",{placeholder:"27AABCS1234A1ZN",maxLength:15}))
          ),
          React.createElement("div",{className:"form-row"},
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"Client Type"),React.createElement("select",null,["CA Firm","Tax Consultant","SME","Enterprise","Accounting Firm"].map(o=>React.createElement("option",{key:o},o)))),
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"Plan"),React.createElement("select",null,["Starter","Pro","Enterprise"].map(o=>React.createElement("option",{key:o},o))))
          ),
          React.createElement("div",{className:"form-row"},
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"Contact Person"),React.createElement("input",{placeholder:"CA / Manager Name"})),
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"Email"),React.createElement("input",{type:"email",placeholder:"contact@firm.com"})),
            React.createElement("div",{className:"form-group"},React.createElement("label",null,"Mobile"),React.createElement("input",{placeholder:"+91 98765 43210"}))
          )
        ),
        React.createElement("div",{className:"modal-ft"},
          React.createElement(Btn,{onClick:()=>setShowAdd(false)},"Cancel"),
          React.createElement(Btn,{cls:"btn-primary",onClick:()=>setShowAdd(false)},"Add Client")
        )
      )
    )
  );
}

// ── INVOICING ─────────────────────────────────────────────────────────────────
function Invoicing(){
  const [selPlan,setSelPlan]=useState("Pro");
  const [payType,setPayType]=useState("monthly"); // "joining" or "monthly"
  const [showInv,setShowInv]=useState(false);
  const [paying,setPaying]=useState(false);
  const [paid,setPaid]=useState(null); // {orderId, amount, plan, type}

  const p=PLANS.find(x=>x.name===selPlan);
  const baseAmt = payType==="joining" ? p.joiningFee : p.price;
  const gstAmt  = +(baseAmt*0.18).toFixed(2);
  const totalAmt = +(baseAmt+gstAmt).toFixed(2);
  const totalPaise = Math.round(totalAmt*100); // Razorpay needs paise

  const invNo="VT/2025-26/INV/"+String(Math.floor(Math.random()*900)+100).padStart(4,"0");
  const today=new Date().toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"});

  // ── Load Razorpay SDK dynamically
  const loadRazorpay=()=>new Promise((res)=>{
    if(window.Razorpay){res(true);return;}
    const s=document.createElement("script");
    s.src="https://checkout.razorpay.com/v1/checkout.js";
    s.onload=()=>res(true);
    s.onerror=()=>res(false);
    document.body.appendChild(s);
  });

  // ── Open Razorpay checkout
  const handlePay=async()=>{
    setPaying(true);
    const ok=await loadRazorpay();
    if(!ok){alert("Failed to load Razorpay. Please check your internet connection.");setPaying(false);return;}
    const options={
      key: CONFIG.RAZORPAY_KEY,
      amount: totalPaise,
      currency: "INR",
      name: CONFIG.RAZORPAY_NAME,
      description: `${CONFIG.PRODUCT} — ${selPlan} Plan (${payType==="joining"?"One-time Joining Fee":"Monthly Subscription"})`,
      image: CONFIG.RAZORPAY_LOGO,
      prefill:{
        name:"",
        email:"",
        contact:""
      },
      notes:{
        plan: selPlan,
        type: payType,
        gstin_seller: CONFIG.GSTIN_VATSA,
        product: CONFIG.PRODUCT,
        fy: CONFIG.FY,
      },
      theme:{ color:"#00B8A9" },
      modal:{ ondismiss:()=>setPaying(false) },
      handler:function(response){
        setPaying(false);
        setPaid({
          orderId: response.razorpay_payment_id,
          amount: totalAmt,
          plan: selPlan,
          type: payType,
          date: today,
          invNo: invNo,
        });
        setShowInv(true);
      }
    };
    const rzp=new window.Razorpay(options);
    rzp.on("payment.failed",function(resp){
      setPaying(false);
      alert("Payment failed: "+resp.error.description+". Please try again.");
    });
    rzp.open();
  };

  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Subscription & Invoicing"),
      React.createElement("p",null,"Pay securely via Razorpay · GST invoices issued by "+CONFIG.COMPANY)
    ),

    // ── Payment type toggle
    React.createElement("div",{className:"card",style:{marginBottom:16}},
      React.createElement("div",{className:"card-hd"},React.createElement("h3",null,"Select Payment Type")),
      React.createElement("div",{style:{display:"flex",gap:10,flexWrap:"wrap"}},
        [["joining","🔑 One-time Joining Fee","Pay once to activate your account"],["monthly","🔄 Monthly Subscription","Pay monthly for continued access"]].map(([k,l,sub])=>
          React.createElement("div",{key:k,
            onClick:()=>setPayType(k),
            style:{flex:1,minWidth:200,padding:"14px 16px",borderRadius:"var(--r)",border:payType===k?"2px solid var(--teal)":"2px solid var(--slate1)",cursor:"pointer",background:payType===k?"var(--teal-light)":"var(--white)",transition:"all .15s"}},
            React.createElement("div",{style:{fontWeight:700,fontSize:13,color:payType===k?"var(--teal)":"var(--slate8)"}},l),
            React.createElement("div",{style:{fontSize:11.5,color:"var(--slate3)",marginTop:2}},sub)
          )
        )
      )
    ),

    // ── Plan cards
    React.createElement("div",{className:"g3"},
      PLANS.map(pl=>React.createElement("div",{key:pl.name,
        className:`plan-card ${pl.featured?"featured":""}`,
        style:{border:selPlan===pl.name?"2px solid var(--teal)":"2px solid var(--slate1)"},
        onClick:()=>setSelPlan(pl.name)},
        React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"}},
          React.createElement("h3",{style:{fontSize:15,fontWeight:800}},pl.name),
          React.createElement(Pill,{type:pl.name==="Enterprise"?"teal":pl.name==="Pro"?"blue":"slate"},pl.name)
        ),

        // Joining fee badge
        React.createElement("div",{style:{background:"#FEF3C7",border:"1px solid #FDE68A",borderRadius:4,padding:"4px 8px",marginTop:10,fontSize:11,color:"#92400E",fontWeight:600}},
          "🔑 Joining Fee: ₹",pl.joiningFee?.toLocaleString("en-IN")," + GST = ₹",(pl.joiningFee*1.18).toFixed(0)
        ),

        // Monthly price
        React.createElement("div",{className:"plan-price"},"₹",pl.price.toLocaleString("en-IN"),React.createElement("span",null,"/month + 18% GST")),
        React.createElement("div",{style:{fontSize:11,color:"var(--slate3)",marginBottom:14}},"Monthly total: ₹",(pl.price*1.18).toFixed(2)," · Clients: ",pl.clients===999?"Unlimited":pl.clients," · Invoices: ",pl.invoices),

        pl.features.map(f=>React.createElement("div",{key:f,className:"plan-feat"},f)),

        React.createElement(Btn,{cls:`${selPlan===pl.name?"btn-primary":"btn-secondary"}`,onClick:(e)=>{e.stopPropagation();setSelPlan(pl.name)}},
          selPlan===pl.name?"✓ Selected":"Select Plan"
        )
      ))
    ),

    // ── Payment summary + Pay button
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"Payment Summary"),
        React.createElement("div",{style:{display:"flex",gap:8}},
          React.createElement(Btn,{sm:true,onClick:()=>setShowInv(true)},"🧾 View Invoice"),
          React.createElement(Btn,{cls:"btn-primary",onClick:handlePay,disabled:paying},
            paying ? React.createElement(React.Fragment,null,React.createElement("div",{className:"spinner"})," Processing...") : "💳 Pay ₹"+totalAmt.toFixed(2)+" via Razorpay"
          )
        )
      ),
      React.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(160px,1fr))",gap:12,marginBottom:14}},
        [
          ["Plan",selPlan],
          ["Payment Type",payType==="joining"?"One-time Joining Fee":"Monthly Subscription"],
          ["Base Amount","₹"+baseAmt.toLocaleString("en-IN")],
          ["GST @18% (CGST 9% + SGST 9%)","₹"+gstAmt],
          ["Total Payable","₹"+totalAmt.toFixed(2)],
          ["Payment Gateway","Razorpay (Secure)"],
        ].map(([l,v])=>
          React.createElement("div",{key:l},
            React.createElement("div",{style:{fontSize:10.5,color:"var(--slate3)",fontWeight:600,textTransform:"uppercase",letterSpacing:".05em",marginBottom:2}},l),
            React.createElement("div",{style:{fontSize:13,fontWeight:700,color:l==="Total Payable"?"var(--teal)":"var(--slate8)"}},v)
          )
        )
      ),
      React.createElement("div",{className:"alert alert-info",style:{marginBottom:0}},
        "🔒 Payments secured by Razorpay. Supports UPI, Net Banking, Credit/Debit Cards, Wallets. GST invoice issued by ",React.createElement("b",null,CONFIG.COMPANY)," (GSTIN: ",CONFIG.GSTIN_VATSA,") upon successful payment."
      )
    ),

    // ── Payment success banner
    paid && React.createElement("div",{className:"alert alert-success",style:{marginTop:14,fontSize:13}},
      "✅ ",React.createElement("b",null,"Payment Successful!")," · Payment ID: ",React.createElement("b",null,paid.orderId)," · ₹",paid.amount," · ",paid.plan," Plan · ",paid.date,
      " · ",React.createElement("span",{style:{color:"var(--teal)",cursor:"pointer",fontWeight:700},onClick:()=>setShowInv(true)},"Download Invoice →")
    ),

    // ── Invoice Modal
    showInv && React.createElement("div",{className:"modal-overlay",onClick:()=>setShowInv(false)},
      React.createElement("div",{className:"modal",style:{width:700},onClick:e=>e.stopPropagation()},
        React.createElement("div",{className:"modal-hd"},
          React.createElement("h2",null,"GST Tax Invoice — ",CONFIG.COMPANY),
          React.createElement("button",{className:"modal-close",onClick:()=>setShowInv(false)},"✕")
        ),
        React.createElement("div",{className:"modal-body"},
          React.createElement("div",{className:"inv-paper"},
            React.createElement("div",{className:"inv-hd"},
              React.createElement("div",null,
                React.createElement("div",{className:"inv-logo-name"},CONFIG.COMPANY),
                React.createElement("div",{className:"inv-logo-tag"},"GST Compliance & Tax Technology Solutions"),
                React.createElement("div",{style:{fontSize:11.5,color:"var(--slate3)",marginTop:8,lineHeight:1.8}},
                  "7A, SRS Flats, Bali Nagar,",React.createElement("br",null),
                  "Near Agra Chowk, Palwal,",React.createElement("br",null),
                  "Haryana — 121102",React.createElement("br",null),
                  "GSTIN: ",CONFIG.GSTIN_VATSA,React.createElement("br",null),
                  "PAN: BENPS9060N",React.createElement("br",null),
                  "Email: kuwarpal@gmail.com",React.createElement("br",null),
                  "State: Haryana (06)"
                )
              ),
              React.createElement("div",{style:{textAlign:"right"}},
                React.createElement("div",{style:{fontSize:20,fontWeight:900,color:"var(--navy)",marginBottom:8}},"TAX INVOICE"),
                React.createElement("div",{className:"inv-meta"},
                  React.createElement("div",null,"Invoice No: ",React.createElement("strong",null,paid?.invNo||invNo)),
                  React.createElement("div",null,"Date: ",React.createElement("strong",null,paid?.date||today)),
                  React.createElement("div",null,"Due: ",React.createElement("strong",null,"Paid via Razorpay")),
                  paid && React.createElement("div",{style:{marginTop:4}},
                    "Payment ID: ",React.createElement("strong",null,paid.orderId)
                  ),
                  React.createElement("br",null),
                  React.createElement(Pill,{type:"green"},"Original for Recipient")
                )
              )
            ),
            React.createElement("hr",{className:"inv-divider"}),
            React.createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:20,marginBottom:16}},
              React.createElement("div",null,
                React.createElement("div",{style:{fontSize:10,fontWeight:700,color:"var(--slate3)",textTransform:"uppercase",letterSpacing:".06em",marginBottom:6}},"Bill To"),
                React.createElement("div",{style:{fontSize:12,lineHeight:1.8}},"[Customer Name]",React.createElement("br",null),"GSTIN: [Customer GSTIN]",React.createElement("br",null),"[City, State]")
              ),
              React.createElement("div",null,
                React.createElement("div",{style:{fontSize:10,fontWeight:700,color:"var(--slate3)",textTransform:"uppercase",letterSpacing:".06em",marginBottom:6}},"Place of Supply"),
                React.createElement("div",{style:{fontSize:12,lineHeight:1.8}},"Haryana (State Code: 06)",React.createElement("br",null),"SAC Code: ",CONFIG.SAC,React.createElement("br",null),"(Information Technology Services)")
              )
            ),
            React.createElement("table",{style:{marginBottom:14}},
              React.createElement("thead",null,React.createElement("tr",null,
                ["#","Description of Service","SAC","Qty","Rate (₹)","Amount (₹)"].map(h=>React.createElement("th",{key:h},h))
              )),
              React.createElement("tbody",null,
                React.createElement("tr",null,
                  React.createElement("td",null,"1"),
                  React.createElement("td",null,
                    React.createElement("b",null,CONFIG.PRODUCT," — ",selPlan," Plan"),React.createElement("br",null),
                    React.createElement("span",{style:{fontSize:11,color:"var(--slate3)"}},
                      payType==="joining"?"One-time Account Activation / Joining Fee":"Monthly Subscription — ",
                      " FY ",CONFIG.FY," · AI-Powered GST Reconciliation Platform"
                    )
                  ),
                  React.createElement("td",{className:"mono"},CONFIG.SAC),
                  React.createElement("td",null,payType==="joining"?"1 (One-time)":"1 Month"),
                  React.createElement("td",{className:"mono"},baseAmt.toLocaleString("en-IN")),
                  React.createElement("td",{className:"mono",style:{fontWeight:700}},baseAmt.toLocaleString("en-IN"))
                )
              )
            ),
            React.createElement("div",{style:{display:"flex",justifyContent:"flex-end"}},
              React.createElement("table",{style:{width:290,fontSize:12.5}},
                React.createElement("tbody",null,
                  [["Taxable Amount","₹"+baseAmt.toLocaleString("en-IN")],["CGST @ 9%","₹"+(baseAmt*0.09).toFixed(2)],["SGST @ 9%","₹"+(baseAmt*0.09).toFixed(2)]].map(([l,v])=>
                    React.createElement("tr",{key:l},
                      React.createElement("td",{style:{padding:"3px 8px",color:"var(--slate3)"}},l),
                      React.createElement("td",{className:"mono",style:{textAlign:"right",padding:"3px 8px"}},v)
                    )
                  ),
                  React.createElement("tr",{style:{borderTop:"2px solid var(--slate8)"}},
                    React.createElement("td",{style:{padding:"8px 8px",fontWeight:800,fontSize:14}},"Total Paid"),
                    React.createElement("td",{className:"mono",style:{textAlign:"right",padding:"8px 8px",fontWeight:800,fontSize:16,color:"var(--teal)"}},"₹",totalAmt.toFixed(2))
                  )
                )
              )
            ),
            React.createElement("hr",{className:"inv-divider"}),
            React.createElement("div",{style:{fontSize:11,color:"var(--slate3)",lineHeight:1.9}},
              React.createElement("b",{style:{color:"var(--slate8)"}},"Payment: "),"Received via Razorpay · Payment ID: ",(paid?.orderId||"Pending"),React.createElement("br",null),
              React.createElement("b",{style:{color:"var(--slate8)"}},"Note: "),"ITC claimable as per GSTR-2B after invoice reflects in supplier's GSTR-1.",React.createElement("br",null),
              React.createElement("b",{style:{color:"var(--slate8)"}},"Legal: "),"Issued under Section 31 of CGST Act 2017 · GST Invoice Rules 2026 · SAC 998314 · 18% GST."
            )
          )
        ),
        React.createElement("div",{className:"modal-ft"},
          React.createElement(Btn,{onClick:()=>setShowInv(false)},"Close"),
          React.createElement(Btn,null,"📧 Email Invoice"),
          React.createElement(Btn,{cls:"btn-primary"},"🖨️ Print / Save PDF")
        )
      )
    )
  );
}

// ── SETTINGS// ── SETTINGS ──────────────────────────────────────────────────────────────────
function Settings(){
  const team=[
    {name:"Rajesh Kumar",email:"rajesh@vatsatraders.com",role:"Super Admin",last:"Today 10:22"},
    {name:"Priya Sharma",email:"priya@vatsatraders.com",role:"CA Manager",last:"Today 9:15"},
    {name:"Amit Patel",email:"amit@vatsatraders.com",role:"Tax Associate",last:"Yesterday"},
    {name:"Sunita Verma",email:"sunita@vatsatraders.com",role:"Viewer",last:"3 days ago"},
  ];
  return React.createElement("div",null,
    React.createElement("div",{className:"pg-hd"},
      React.createElement("h2",null,"Settings & Administration"),
      React.createElement("p",null,"Manage team members, roles, organisation settings, and audit logs")
    ),
    React.createElement("div",{className:"g2"},
      React.createElement("div",{className:"card"},
        React.createElement("div",{className:"card-hd"},
          React.createElement("h3",null,"Team Management"),
          React.createElement(Btn,{sm:true,cls:"btn-primary"},"+ Invite User")
        ),
        team.map(u=>React.createElement("div",{key:u.email,style:{display:"flex",alignItems:"center",gap:12,padding:"10px 0",borderBottom:"1px solid var(--slate1)"}},
          React.createElement("div",{className:"tb-avatar"},u.name[0]),
          React.createElement("div",{style:{flex:1}},
            React.createElement("div",{style:{fontWeight:600,fontSize:13}},u.name),
            React.createElement("div",{style:{fontSize:11,color:"var(--slate3)"}},u.email)
          ),
          React.createElement("div",{style:{textAlign:"right"}},
            React.createElement(Pill,{type:u.role==="Super Admin"?"teal":u.role==="CA Manager"?"blue":"slate"},u.role),
            React.createElement("div",{style:{fontSize:10,color:"var(--slate3)",marginTop:2}},u.last)
          )
        ))
      ),
      React.createElement("div",{className:"card"},
        React.createElement("div",{className:"card-hd"},React.createElement("h3",null,"Organisation Settings")),
        [["Business Name",CONFIG.COMPANY,"text"],["GSTIN",CONFIG.GSTIN_VATSA,"text"],["Financial Year",null,"select"],["State","Haryana — Palwal","text"],["AI API Key","sk-ant-••••••••","password"]].map(([l,v,t])=>
          React.createElement("div",{key:l,className:"form-group",style:{marginBottom:12}},
            React.createElement("label",null,l),
            t==="select"
              ? React.createElement("select",null,FYS.map(f=>React.createElement("option",{key:f},f)))
              : React.createElement("input",{type:t,defaultValue:v||""})
          )
        ),
        React.createElement(Btn,{cls:"btn-primary"},"Save Settings")
      )
    ),
    React.createElement("div",{className:"card"},
      React.createElement("div",{className:"card-hd"},
        React.createElement("h3",null,"Audit Log"),
        React.createElement(Btn,{sm:true},"📥 Export Log")
      ),
      React.createElement("div",{className:"tbl-wrap"},
        React.createElement("table",null,
          React.createElement("thead",null,React.createElement("tr",null,
            ["Timestamp","User","Action","Module","IP Address"].map(h=>React.createElement("th",{key:h},h))
          )),
          React.createElement("tbody",null,
            [
              ["16-Jun-25 10:22","Rajesh Kumar","Ran GSTR-2B Reconciliation — May 2025","Reconciliation","103.24.56.78"],
              ["16-Jun-25 09:15","Priya Sharma","Uploaded GSTR-2B JSON — May 2025","Import","103.24.56.79"],
              ["15-Jun-25 18:40","Amit Patel","Generated Mismatch Report (PDF)","Reports","103.24.56.80"],
              ["15-Jun-25 14:10","Rajesh Kumar","Added Client: Patel & Co CA","Clients","103.24.56.78"],
              ["14-Jun-25 11:30","Priya Sharma","AI Query: Vendor risk analysis","AI Assistant","103.24.56.79"],
              ["14-Jun-25 09:00","Rajesh Kumar","Generated Invoice VT/2025-26/INV/0046","Invoicing","103.24.56.78"],
            ].map(([ts,u,a,m,ip])=>
              React.createElement("tr",{key:ts},
                React.createElement("td",{style:{fontSize:11}},ts),
                React.createElement("td",{style:{fontWeight:600}},u),
                React.createElement("td",null,a),
                React.createElement("td",null,React.createElement(Pill,{type:"slate"},m)),
                React.createElement("td",{className:"mono",style:{fontSize:11}},ip)
              )
            )
          )
        )
      )
    )
  );
}

// ── NAV ───────────────────────────────────────────────────────────────────────
const NAV=[
  {k:"dashboard",icon:"📊",label:"Dashboard"},
  {k:"import",icon:"📥",label:"Import Data"},
  {k:"reconcile",icon:"🔄",label:"Reconciliation",badge:"12"},
  {k:"vendors",icon:"🏢",label:"Vendor Analysis"},
  {k:"reports",icon:"📋",label:"Reports"},
  {k:"compliance",icon:"📅",label:"Compliance",badge:"2"},
  {k:"ai",icon:"🤖",label:"AI Assistant"},
  {k:"clients",icon:"👥",label:"Clients"},
  {k:"invoicing",icon:"🧾",label:"Invoicing"},
  {k:"settings",icon:"⚙️",label:"Settings"},
];

// ── ROOT APP ──────────────────────────────────────────────────────────────────
function App(){
  const [page,setPage]=useState("dashboard");
  const pages={
    dashboard:React.createElement(Dashboard,{onNav:setPage}),
    import:React.createElement(ImportData),
    reconcile:React.createElement(Reconciliation),
    vendors:React.createElement(VendorAnalysis),
    reports:React.createElement(Reports),
    compliance:React.createElement(Compliance),
    ai:React.createElement(AIAssistant),
    clients:React.createElement(Clients),
    invoicing:React.createElement(Invoicing),
    settings:React.createElement(Settings),
  };
  const cur=NAV.find(n=>n.k===page);
  return React.createElement(React.Fragment,null,
    React.createElement("style",null,STYLES),
    React.createElement("div",{className:"app"},
      // Sidebar
      React.createElement("aside",{className:"sidebar"},
        React.createElement("div",{className:"sb-logo"},
          React.createElement("div",{className:"sb-logo-title"},"ProfitPulse ",React.createElement("span",null,"GST Pro")),
          React.createElement("div",{className:"sb-logo-sub"},"by "+CONFIG.COMPANY),
          React.createElement("div",{className:"sb-fy"},"FY "+CONFIG.FY)
        ),
        React.createElement("div",{style:{padding:"6px 0",flex:1}},
          React.createElement("div",{className:"sb-section"},"Main"),
          NAV.slice(0,6).map(n=>React.createElement("div",{key:n.k,className:`sb-item ${page===n.k?"active":""}`,onClick:()=>setPage(n.k)},
            React.createElement("span",{className:"si"},n.icon),
            React.createElement("span",null,n.label),
            n.badge&&React.createElement("span",{className:"sb-badge"},n.badge)
          )),
          React.createElement("div",{className:"sb-section"},"Management"),
          NAV.slice(6).map(n=>React.createElement("div",{key:n.k,className:`sb-item ${page===n.k?"active":""}`,onClick:()=>setPage(n.k)},
            React.createElement("span",{className:"si"},n.icon),
            React.createElement("span",null,n.label),
            n.badge&&React.createElement("span",{className:"sb-badge"},n.badge)
          ))
        ),
        React.createElement("div",{className:"sb-footer"},
          React.createElement("p",null,CONFIG.PRODUCT,React.createElement("br",null),"v",CONFIG.VERSION," · FY ",CONFIG.FY,React.createElement("br",null),"GST Rules 2026",React.createElement("br",null),"© ",CONFIG.COMPANY)
        )
      ),
      // Main
      React.createElement("div",{className:"main"},
        React.createElement("div",{className:"topbar"},
          React.createElement("div",null,
            React.createElement("div",{className:"tb-title"},cur?.label||"Dashboard"),
            React.createElement("div",{className:"tb-sub"},CONFIG.PRODUCT+" · "+CONFIG.COMPANY)
          ),
          React.createElement("div",{className:"tb-spacer"}),
          React.createElement("div",{className:"fy-chip"},"FY "+CONFIG.FY),
          React.createElement("button",{className:"btn btn-secondary btn-sm"},"🔔 Alerts"),
          React.createElement("button",{className:"btn btn-secondary btn-sm",onClick:()=>setPage("ai")},"🤖 Ask AI"),
          React.createElement("div",{className:"tb-avatar",title:CONFIG.COMPANY},"VT")
        ),
        React.createElement("div",{className:"content"},pages[page])
      )
    )
  );
}

// ── MOUNT ─────────────────────────────────────────────────────────────────────
const root=ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(App));
