// VerityOne — Special Investigations Unit Portal (post-login case management)

const CASE = {
  title: 'Foundry & Freight Co. — Fire Damage Claim',
  ref: 'VC-2026-004417',
  policy: 'UK-2020-10112546',
  policyholder: 'Joseph Carter',
  premises: 'Unit 4, Northgate Business Park, Rotherham, South Yorkshire',
  amount: '£2,500,000',
  submitted: '17 June 2026',
  approved: '20 June 2026',
  approvedBy: 'B. Foster',
  payout: '22 June 2026',
  email: 'josephc@outlook.com',
  business: 'Metal fabrication & freight/haulage'
};

// `file` is where the in-portal viewer looks for the real document
const DOCS = [
  { type: 'PDF', t: 'Policy Schedule', m: 'VerityOne Insurance · Issued 2 Feb 2026', file: 'documents/policy-schedule.pdf' },
  { type: 'PDF', t: 'Statement of Insurance', m: 'Standard terms · all VerityOne Commercial Combined policies', file: 'documents/statement-of-insurance.pdf' },
  { type: 'PDF', t: 'Claim Form', m: 'Claim Submission Form · VerityOne Commercial Combined policies · 14 June 2026', file: 'documents/claim-form.pdf' },
  { type: 'PDF', t: 'Fire Investigation Report', m: 'NorthWest Fire Investigation Services Ltd · 12 June 2026', file: 'documents/fire-investigation-report.pdf' },
  { type: 'PDF', t: 'Contractor Quote', m: 'Kingsley Restoration & Building Ltd · 15 June 2026', file: 'documents/contractor-quote.pdf' },
  //{ type: 'PDF', t: 'Site Photographs', m: 'Field capture · 11 June 2026', file: 'documents/site-photographs.pdf' }
];

const COMMUNICATIONS_CODE = 'VTO455';

const PROCESSING_HISTORY = [
  { date: '14 Jun 2026', t: 'Claim Submitted', sub: 'By: Joseph Carter | VerityOne Customer Portal', state: 'done' },
  { date: '15 Jun 2026', t: 'Supporting Documents Uploaded', sub: 'By: Joseph Carter', state: 'done',
    includes: ['Fire Investigation Report', 'Scene Photographs', 'Contractor Quotation'] },
  { date: '16 Jun 2026', t: 'Claim Review Initiated', sub: 'By: Billy Foster | Commercial Claims', state: 'done' },
  { date: '17 Jun 2026', t: 'Loss Assessment Completed', sub: 'By: Claire Wilson | Loss Adjuster', state: 'done' },
  { date: '18 Jun 2026', t: 'Compliance Review Completed', sub: 'By: Compliance Team', state: 'done' },
  { date: '20 Jun 2026', t: 'Approved for Payment', sub: 'By: Finance Manager', state: 'done' },
  { date: '', t: 'SIU Investigation', sub: 'Pending | Assigned by: Eleanor Brooks', state: 'current' },
  { date: '22 Jun 2026', t: 'Scheduled Payout', sub: 'Pending', state: 'pending' }
];

const SiuTopbar = ({ onSignOut }) => (
  <div className="siu-topbar">
    <div className="siu-brand">
      <span className="b-main">VerityOne SIU</span>
      <span className="b-sub">Case Management System</span>
    </div>
    <div className="siu-search">
      <span className="s-icon"><Icon name="search" size={15} /></span>
      <input placeholder="Search cases, policies, claimants…" />
    </div>
    <div className="siu-topbar-right">
      <span className="siu-clearance">Clearance: Standard</span>
      <span className="siu-bell"><Icon name="bell" size={18} /><span className="dot"></span></span>
      <div className="siu-user">
        <span className="avatar">JI</span>
        <span className="u-name" style={{ textAlign: 'center' }}>Signed in as<br/>Junior Investigator</span>
      </div>
      <button className="siu-signout" onClick={onSignOut}>Sign out</button>
    </div>
  </div>
);

const SiuSidebar = ({ tab, setTab, commsUnlocked }) => {
  const items = [
    { id: 'overview', label: 'Overview' },
    { id: 'documents', label: 'Documents' },
    { id: 'correspondence', label: 'Communications', locked: !commsUnlocked },
    { id: 'audit', label: 'Audit Log', locked: true },
    { id: 'directory', label: 'Staff Directory', locked: true }
  ];
  return (
    <div className="siu-side">
      <div className="side-head">Case File</div>
      {items.map((it) => (
        <div key={it.id}
          className={`side-item ${tab === it.id ? 'active' : ''} ${it.locked ? 'locked' : ''}`}
          onClick={() => setTab(it.id)}>
          <span>{it.label}</span>
          {it.locked && <span className="lk"><Icon name="lock" size={13} /></span>}
        </div>
      ))}
    </div>
  );
};

const CaseHeader = () => (
  <div className="siu-card case-head">
    <div className="top">
      <div>
        <h1>{CASE.title}</h1>
        <div className="refline">Claim Reference: <b>{CASE.ref}</b> &nbsp;·&nbsp; Policy Number: <b>{CASE.policy}</b></div>
      </div>
      <span className="status-badge approved">Approved — Pending Payout</span>
    </div>
    <div className="case-grid">
      <div className="cell"><div className="k">Policyholder</div><div className="v">{CASE.policyholder}</div></div>
      <div className="cell"><div className="k">Insured Premises</div><div className="v plain">{CASE.premises}</div></div>
      <div className="cell"><div className="k">Claimed Amount</div><div className="v">{CASE.amount}</div></div>
      <div className="cell"><div className="k">Claim Submitted</div><div className="v">{CASE.submitted}</div></div>
      <div className="cell"><div className="k">Approved</div><div className="v">{CASE.approved}</div></div>
      <div className="cell"><div className="k">Approved By</div><div className="v">{CASE.approvedBy}</div></div>
      <div className="cell"><div className="k">Scheduled Payout</div><div className="v alert">{CASE.payout}</div></div>
      <div className="cell"><div className="k">Correspondence Email</div><div className="v plain">{CASE.email}</div></div>
      <div className="cell"><div className="k">Business Description</div><div className="v plain">{CASE.business}</div></div>
    </div>
  </div>
);

const DocRow = ({ d, onView }) => (
  <div className="doc-row">
    <div className={`doc-ico ${d.type === 'PDF' ? 'pdf' : ''}`}>{d.type}</div>
    <div className="doc-info">
      <div className="t">{d.t}{d.flag && <span className="doc-flag">{d.flag}</span>}</div>
      <div className="m">{d.m}</div>
    </div>
    <button className="doc-btn" onClick={() => onView(d)}>View</button>
  </div>
);

// Checks the file actually exists before deciding how to render it, so a
// document that hasn't been dropped into documents/ yet fails gracefully
// instead of the iframe/img just showing a broken/blank state.
const DocPreview = ({ doc }) => {
  const [status, setStatus] = React.useState('loading');

  React.useEffect(() => {
    let alive = true;
    setStatus('loading');
    fetch(doc.file, { method: 'HEAD', cache: 'no-store' })
      .then((res) => alive && setStatus(res.ok ? 'ready' : 'missing'))
      .catch(() => alive && setStatus('missing'));
    return () => { alive = false; };
  }, [doc.file]);

  if (status === 'loading') {
    return <div className="doc-preview-state"><span>Loading preview…</span></div>;
  }

  if (status === 'missing') {
    return (
      <div className="doc-preview-state doc-preview-missing">
        <div className="dp-ico"><Icon name="file" size={24} /></div>
        <div className="dp-t">Not uploaded yet</div>
        <div className="dp-d">
          Drop the file at <code>{doc.file}</code> in the project folder and reopen this
          document to preview it here.
        </div>
      </div>
    );
  }

  const ext = doc.file.split('.').pop().toLowerCase();
  if (['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {
    return <img className="doc-frame doc-frame-img" src={doc.file} alt={doc.t} />;
  }
  return <iframe className="doc-frame" src={doc.file} title={doc.t} />;
};

const DocViewerModal = ({ doc, onClose }) => (
  <div className="modal-backdrop" onClick={onClose}>
    <div className="doc-viewer" onClick={(e) => e.stopPropagation()}>
      <div className="dv-head">
        <div>
          <div className="dv-t">{doc.t}{doc.flag && <span className="doc-flag">{doc.flag}</span>}</div>
          <div className="dv-m">{doc.m}</div>
        </div>
        <div className="dv-actions">
          <a className="btn btn-secondary btn-small" href={doc.file} target="_blank" rel="noreferrer">
            Open in new tab <Icon name="arrow" size={14} />
          </a>
          <button className="dv-close" aria-label="Close" onClick={onClose}>×</button>
        </div>
      </div>
      <div className="dv-body">
        <DocPreview doc={doc} />
      </div>
    </div>
  </div>
);

const ClaimHistoryCard = () => (
  <div className="siu-card">
    <div className="blk-head"><h2>Claim Processing History</h2></div>
    <div className="stepper stepper-wide">
      {PROCESSING_HISTORY.map((s, i) => (
        <div key={i} className={`step-item ${s.state}`}>
          <div className="marker"></div>
          <div className="st-row">
            <div className="st-txt">
              <div className="st-t">{s.t}</div>
              <div className="st-d">{s.sub}</div>
              {s.includes &&
                <div className="st-chips">
                  {s.includes.map((doc, j) => <span key={j} className="st-chip">{doc}</span>)}
                </div>
              }
            </div>
            <div className="st-date">{s.date}</div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const AlertsCard = () => (
  <div className="rail-card">
    <div className="rc-head">Claim Insights</div>
    <div className="rc-body">
      <div className="alert-item hot">
        <span className="alert-ico warn"><Icon name="award" size={18} /></span>
        <div className="alert-body"><div className="al-t">High-Value Claim</div><div className="al-d">Claimed amount exceeds £1,500,000, senior approval required before payout.</div></div>
      </div>
      <div className="alert-item">
        <span className="alert-ico ok"><Icon name="file" size={18} /></span>
        <div className="alert-body"><div className="al-t">Supporting Documentation</div><div className="al-d">All required documents have been received.</div></div>
      </div>
      <div className="alert-item">
        <span className="alert-ico ok"><Icon name="check" size={18} /></span>
        <div className="alert-body"><div className="al-t">Automated Fraud Screening</div><div className="al-d">No high-risk indicators detected</div></div>
      </div>
    </div>
  </div>
);

const OverviewTab = () => (
  <div className="siu-main">
    <CaseHeader />
    <div className="ov-split">
      <ClaimHistoryCard />
      <div className="siu-rail">
        <AlertsCard />
      </div>
    </div>
  </div>
);

const DocumentsTab = () => {
  const [viewing, setViewing] = React.useState(null);
  return (
    <div className="siu-main">
      <div className="siu-card">
        <div className="blk-head"><h2>Case Documents</h2><span className="link">{DOCS.length} files</span></div>
        {DOCS.map((d, i) => <DocRow key={i} d={d} onView={setViewing} />)}
      </div>
      {viewing && <DocViewerModal doc={viewing} onClose={() => setViewing(null)} />}
    </div>
  );
};

const CommunicationsTab = () => {
  const items = [
    { from: 'Joseph Carter', addr: 'josephc@outlook.com', date: '25 May 2026', subj: 'Request to update correspondence email', prev: 'Good afternoon! I no longer have access to my previous email address. Please update my primary correspondence email to this address for all future policy and claim communications. Kind regards, Joseph Carter.' },
    { from: 'VerityOne Customer Services', addr: 'customersevices@verityone-insurance.co.uk', date: '24 May 2026', subj: 'Confirmation of Correspondence Details', prev: 'Dear Mr. Carter, your primary correspondence email has been successfully updated. Future communications relating to your policy will be sent to this address.' },
    { from: 'Joseph Carter', addr: 'josephc@outlook.com', date: '12 June 2026', subj: 'Commercial Fire Claim - Next Steps', prev: 'Good morning. My warehouse has had a recent fire, could you please advise on the claims process and the documentation required to begin my claim? Many thanks.'},
    { from: 'Claims Team', addr: 'commercialclaims@verityone-insurance.co.uk', date: '12 June 2026', subj: 'Re - Required documents for commericial property fire claim', prev: 'Dear Mr. Carter, thank you for notifying us of the incident. To progress your claim, please submit the completed claim form together with the fire investigation report, photographs of the damage, contractor quotations and any supporting documentation through the Policyholder Portal.'},
    { from: 'Joseph Carter', addr: 'josephc@outlook.com', date: '15 June 2026', subj: 'Claim documents submitted', prev: 'Good afternoon. I have now uploaded the completed claim form and all requested supporting documents through the Policyholder Portal. Please let me know if anything further is required.'},
    { from: 'Billy Foster', addr: 'billyfoster@verityone.co.uk', date: '18 Jun 2026', subj: 'Assessment complete — VC-2026-004417', prev: 'Dear Joseph, I have reviewed your documents and the compliance team has also signed it off. There will be no problem during payout which is scheduled for 22 June 2026.' }
  ];
  return (
    <div className="siu-main">
      <div className="siu-card">
        <div className="blk-head"><h2>Communications</h2><span className="link">6 threads</span></div>
        {items.map((c, i) => (
          <div key={i} className="corr-item">
            <div className="c-top">
              <div className="c-from">{c.from} <span>&lt;{c.addr}&gt;</span></div>
              <div className="c-date">{c.date}</div>
            </div>
            <div className="c-subj">{c.subj}</div>
            <div className="c-prev">{c.prev}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// Communications is unlocked with its own 6-character access code, entered
// right on this page — distinct from Audit Log/Staff Directory, which stay
// gated behind the investigator's overall clearance level instead.
const CommunicationsGate = ({ onUnlock }) => {
  const [code, setCode] = React.useState('');
  const [error, setError] = React.useState(false);

  const onSubmit = (e) => {
    e.preventDefault();
    if (code.trim().toUpperCase() === COMMUNICATIONS_CODE.toUpperCase()) {
      onUnlock();
    } else {
      setError(true);
    }
  };

  return (
    <div className="siu-main">
      <div className="siu-card locked-panel">
        <div className="lp-ico"><Icon name="lock" size={28} /></div>
        <h2>Communications is restricted</h2>
        <p>This channel is encrypted. Enter the 6-character access code to view correspondence for this case.</p>
        <form className="unlock-form" onSubmit={onSubmit}>
          <input
            className={`unlock-input ${error ? 'error' : ''}`}
            value={code}
            onChange={(e) => { setCode(e.target.value.toUpperCase().slice(0, 6)); setError(false); }}
            placeholder="——————"
            maxLength={6}
            autoComplete="off"
            spellCheck={false}
            aria-label="Access code"
          />
          <button type="submit" className="btn btn-primary btn-small">Unlock</button>
        </form>
        {error && <div className="unlock-error">Incorrect code. Please try again.</div>}
      </div>
    </div>
  );
};

const LockedTab = ({ name }) => (
  <div className="siu-main">
    <div className="siu-card locked-panel">
      <div className="lp-ico"><Icon name="lock" size={28} /></div>
      <h2>{name} is restricted</h2>
      <p>Your current clearance level does not permit access to this section. Elevated access is granted to Senior Investigators and above.</p>
      <p>To request access, contact your unit supervisor or the Information Security team.</p>
      <div className="req">Required clearance: Elevated &nbsp;·&nbsp; Your clearance: Standard</div>
    </div>
  </div>
);

// Investigation Mode — Companies Register lookup ---------------------------
// Name and number searches are kept deliberately independent: a query that
// looks like a company number only ever matches companyNumber, anything
// else only ever matches companyName. That's what lets the same number
// surface a completely unrelated company on the register — the tool exists
// to expose that mismatch, not to paper over it with fuzzy matching.
const COMPANIES_REGISTER = [
  {
    companyName: 'VerityOne Insurance',
    companyNumber: '01984523',
    status: 'Active',
    incorporatedOn: '3 September 2003',
    companyType: 'Private limited company',
    registeredAddress: 'VerityOne House, 46 Cornhill, London EC3V 3ND',
    sic: '65120 - Non-life insurance'
  },
  {
    companyName: 'Bright Nails & Beauty Ltd',
    companyNumber: '03350142',
    status: 'Active',
    incorporatedOn: '19 August 2016',
    companyType: 'Private limited company',
    registeredAddress: '45 Kirkgate, Leeds, West Yorkshire LS1 6BY',
    sic: '96020 - Hairdressing and other beauty treatment'
  },
  {
    companyName: 'NorthWest Fire Investigation Services Ltd',
    companyNumber: '09873421',
    status: 'Dissolved',
    dissolvedOn: '2 March 2026',
    incorporatedOn: '14 May 2014',
    companyType: 'Private limited company',
    registeredAddress: 'Unit 12, Colville Business Centre, Manchester M4 5HU',
    sic: '80300 - Investigation activities'
  }
];

function lookupCompany(query) {
  const q = query.trim();
  if (!q) return null;
  const digitsOnly = q.replace(/\s+/g, '');
  if (/^[0-9]+$/.test(digitsOnly)) {
    return COMPANIES_REGISTER.find((c) => c.companyNumber === digitsOnly) || null;
  }
  const needle = q.toLowerCase();
  return COMPANIES_REGISTER.find((c) => c.companyName.toLowerCase().includes(needle)) || null;
}

const CompanyResultCard = ({ c }) => (
  <div className="inv-result">
    <div className="inv-result-head">
      <div className="inv-result-name">{c.companyName}</div>
      <span className={`inv-status ${c.status === 'Active' ? 'active' : 'dissolved'}`}>{c.status}</span>
    </div>
    <div className="inv-result-grid">
      <div className="cell"><div className="k">Company Number</div><div className="v">{c.companyNumber}</div></div>
      {c.status === 'Dissolved' &&
        <div className="cell"><div className="k">Dissolved On</div><div className="v alert">{c.dissolvedOn}</div></div>
      }
      <div className="cell"><div className="k">Incorporated On</div><div className="v">{c.incorporatedOn}</div></div>
      <div className="cell"><div className="k">Company Type</div><div className="v">{c.companyType}</div></div>
      <div className="cell full"><div className="k">Registered Office Address</div><div className="v">{c.registeredAddress}</div></div>
      <div className="cell full"><div className="k">Nature of Business (SIC)</div><div className="v">{c.sic}</div></div>
    </div>
  </div>
);

const CompaniesRegisterTool = () => {
  const [query, setQuery] = React.useState('');
  const [searched, setSearched] = React.useState('');
  const result = searched ? lookupCompany(searched) : null;

  const onSubmit = (e) => {
    e.preventDefault();
    setSearched(query.trim());
  };

  return (
    <div className="inv-tool">
      <form className="inv-search" onSubmit={onSubmit}>
        <span className="inv-search-ico"><Icon name="search" size={15} /></span>
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Company name or company number…"
        />
        <button type="submit" className="inv-search-btn">Search</button>
      </form>

      {!searched &&
        <div className="inv-hint">
          Enter a company name or an 8-digit company number to pull its Companies House record.
        </div>
      }

      {searched && result && <CompanyResultCard c={result} />}

      {searched && !result &&
        <div className="inv-empty">
          <div className="inv-empty-ico"><Icon name="search" size={22} /></div>
          <div className="inv-empty-t">No results found for "{searched}"</div>
          <div className="inv-empty-d">No active or dissolved record matches that name or number. Try the other identifier if you have it.</div>
        </div>
      }
    </div>
  );
};

// Add future tools here as { id, label, render } — the tab strip and panel
// shell below don't need to change when a new tab is added.
const INVESTIGATION_TABS = [
  { id: 'companies', label: 'Companies Register', render: () => <CompaniesRegisterTool /> }
];

const InvestigationPanel = ({ onClose }) => {
  const [tab, setTab] = React.useState(INVESTIGATION_TABS[0].id);
  const active = INVESTIGATION_TABS.find((t) => t.id === tab) || INVESTIGATION_TABS[0];
  return (
    <div className="inv-panel">
      <div className="inv-head">
        <div className="inv-head-title"><Icon name="bulb" size={15} /> Investigation Mode</div>
        <button className="inv-close" aria-label="Close Investigation Mode" onClick={onClose}>×</button>
      </div>
      <div className="inv-tabs">
        {INVESTIGATION_TABS.map((t) => (
          <button key={t.id} className={`inv-tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>
      <div className="inv-body">
        {active.render()}
      </div>
    </div>
  );
};

const Portal = ({ onSignOut }) => {
  const [tab, setTab] = React.useState('overview');
  const [investigating, setInvestigating] = React.useState(false);
  const [commsUnlocked, setCommsUnlocked] = React.useState(false);
  const body = {
    overview: <OverviewTab />,
    documents: <DocumentsTab />,
    correspondence: commsUnlocked
      ? <CommunicationsTab />
      : <CommunicationsGate onUnlock={() => setCommsUnlocked(true)} />,
    audit: <LockedTab name="Audit Log" />,
    directory: <LockedTab name="Staff Directory" />
  };
  return (
    <div className={`siu ${investigating ? 'siu--investigating' : ''}`} data-screen-label="SIU Portal">
      <SiuTopbar onSignOut={onSignOut} />
      <div className="siu-wrap">
        <div className="siu-crumbs">My Cases <span className="sep">›</span> <span className="cur">{CASE.policy}</span></div>
        <div className="siu-layout">
          <SiuSidebar tab={tab} setTab={setTab} commsUnlocked={commsUnlocked} />
          {body[tab]}
        </div>
      </div>

      {!investigating &&
        <button className="inv-trigger" aria-label="Open Investigation Mode" title="Investigation Mode"
                onClick={() => setInvestigating(true)}>
          <Icon name="bulb" size={24} />
        </button>
      }

      {investigating && <InvestigationPanel onClose={() => setInvestigating(false)} />}
    </div>
  );
};

Object.assign(window, { Portal });
