/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Search icon ----------
function SearchIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="7" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

function ArrowRight({ size = 12 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="5" y1="12" x2="19" y2="12" />
      <polyline points="13 6 19 12 13 18" />
    </svg>
  );
}

// ---------- Top Nav ----------
function Nav({ navigate }) {
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    if (menuOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [menuOpen]);

  const handleLinkClick = (target) => {
    setMenuOpen(false);
    navigate(target);
  };

  return (
    <header className="nav">
      <div className="nav-inner" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="brand" onClick={() => handleLinkClick('home')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '12px' }}>
          <img src="cayman-compliance-desk-logo.png" alt="Cayman Compliance Desk Logo" style={{ height: '32px', width: 'auto' }} />
          <span>Cayman Compliance Desk</span>
        </div>
        
        <button 
          className={`nav-toggle ${menuOpen ? 'open' : ''}`} 
          onClick={() => setMenuOpen(!menuOpen)} 
          aria-label="Toggle menu"
        >
          <span></span>
          <span></span>
          <span></span>
        </button>

        <nav className={`nav-links ${menuOpen ? 'open' : ''}`}>
          <a onClick={() => handleLinkClick('services')} style={{ cursor: 'pointer' }}>Services</a>
          <a onClick={() => handleLinkClick('how-it-works')} style={{ cursor: 'pointer' }}>How It Works</a>
          <a onClick={() => handleLinkClick('pricing')} style={{ cursor: 'pointer' }}>Pricing</a>
          <a onClick={() => handleLinkClick('why-us')} style={{ cursor: 'pointer' }}>Why Us</a>
          <a onClick={() => handleLinkClick('faq')} style={{ cursor: 'pointer' }}>FAQ</a>
          <a href="https://ditc.caymandesk.com" target="_blank" rel="noopener noreferrer">Regulations Guide</a>
          <a className="btn btn-primary" onClick={() => handleLinkClick('diagnostic')} style={{ color: '#f5ebd9', padding: '8px 16px', fontSize: '11px', fontWeight: '600', letterSpacing: '0.12em', cursor: 'pointer' }}>Free Diagnostic</a>
        </nav>
      </div>
    </header>
  );
}

// ---------- Hero search demo ----------
const SAMPLE_INDEX = [
  { q: 'director', results: [
    { h: 'Directors Registration and Licensing Act, 2014', s: 'Section 2). [director] Categories. Registered [directors]. Definition: Natural persons acting as [directors]…' },
    { h: 'Director Registration and Licensing', s: '[Director] Registration and Licensing. Summary The regulatory regime governing individuals and entities…' },
    { h: 'Directors Registration and Licensing (Amendment) Act, 2023', s: '[Directors] Registration and Licensing (Amendment) Act, 2023. Summary An amendment expanding criminal…' },
    { h: 'Companies Act (2025 Revision) — Part V', s: 'Duties of [directors]. Standards of care, fiduciary obligations, and conflicts of interest…' },
  ]},
  { q: 'aml', results: [
    { h: 'Anti-Money Laundering Regulations (2025 Revision)', s: 'Comprehensive [AML] obligations for persons carrying out relevant financial business in or from Cayman.' },
    { h: 'Guidance Notes on the Prevention of Money Laundering', s: 'CIMA-issued [AML] guidance: risk-based approach, customer due diligence, suspicious activity reporting…' },
    { h: 'Proceeds of Crime Act (2024 Revision)', s: 'Predicate offences and the [AML] reporting framework administered by the Financial Reporting Authority.' },
  ]},
  { q: 'beneficial owner', results: [
    { h: 'Beneficial Ownership Transparency Act, 2023', s: 'Definitions of [beneficial owner], reportable changes, and registrable particulars for entities…' },
    { h: 'BO Regulations (2024 Revision)', s: 'Implementing rules for the [beneficial ownership] regime, including timelines and exemptions.' },
  ]},
  { q: 'cdd', results: [
    { h: 'AML Regulations — Part III', s: '[Customer due diligence] requirements: identification, verification, and ongoing monitoring obligations.' },
    { h: 'Enhanced Due Diligence — Sectoral Guidance', s: '[CDD] uplift triggers for higher-risk relationships and PEP screening.' },
  ]},
  { q: 'fund', results: [
    { h: 'Mutual Funds Act (2025 Revision)', s: 'Registration, licensing, and audit obligations for [funds] established in or from Cayman.' },
    { h: 'Private Funds Act (2025 Revision)', s: 'Scope, registration triggers, and operating conditions for closed-ended [funds].' },
  ]},
];

function HeroSearch() {
  const [q, setQ] = useState('director');
  const [open, setOpen] = useState(true);
  const inputRef = useRef(null);

  // Auto-cycle the demo query so the page feels alive
  const queries = ['director', 'aml', 'beneficial owner', 'cdd', 'fund'];
  const [cycleIdx, setCycleIdx] = useState(0);
  const [typing, setTyping] = useState(true);
  const userTouched = useRef(false);

  useEffect(() => {
    if (userTouched.current) return;
    let cancelled = false;
    const target = queries[cycleIdx];
    let i = 0;

    function tick() {
      if (cancelled || userTouched.current) return;
      if (typing) {
        if (i <= target.length) {
          setQ(target.slice(0, i));
          i += 1;
          setTimeout(tick, 75);
        } else {
          setTimeout(() => { if (!cancelled && !userTouched.current) { setTyping(false); tick(); } }, 1800);
        }
      } else {
        if (q.length > 0) {
          setQ(prev => prev.slice(0, -1));
          setTimeout(tick, 35);
        } else {
          setCycleIdx((cycleIdx + 1) % queries.length);
          setTyping(true);
        }
      }
    }
    setTimeout(tick, 200);
    return () => { cancelled = true; };
    // eslint-disable-next-line
  }, [cycleIdx, typing]);

  function handleChange(e) {
    userTouched.current = true;
    setQ(e.target.value);
    setOpen(true);
  }
  function handleClear() {
    userTouched.current = true;
    setQ('');
    inputRef.current?.focus();
  }

  const result = useMemo(() => {
    if (!q.trim()) return null;
    const lower = q.toLowerCase();
    const exact = SAMPLE_INDEX.find(r => r.q === lower);
    if (exact) return exact;
    // partial match
    const partial = SAMPLE_INDEX.find(r => r.q.startsWith(lower) || lower.startsWith(r.q));
    return partial || { q: lower, results: SAMPLE_INDEX[0].results };
  }, [q]);

  function highlight(text) {
    // Wrap [token] markers with mark
    const parts = text.split(/(\[[^\]]+\])/g);
    return parts.map((p, i) => {
      if (p.startsWith('[') && p.endsWith(']')) {
        return <mark key={i}>{p.slice(1, -1)}</mark>;
      }
      return <React.Fragment key={i}>{p}</React.Fragment>;
    });
  }

  return (
    <div className="hero-search-wrap" onMouseEnter={() => { userTouched.current = true; }}>
      <div className="hero-search">
        <SearchIcon size={16} />
        <input
          ref={inputRef}
          value={q}
          onChange={handleChange}
          onFocus={() => setOpen(true)}
          placeholder="Try: director, aml, beneficial owner…"
        />
        {q && <button className="clear-btn" onClick={handleClear}>Clear</button>}
      </div>
      {open && result && q.trim() && (
        <div className="hero-results">
          <div className="count">{result.results.length * 11 + 1} results for <strong style={{ color: 'var(--ink)' }}>{q}</strong></div>
          {result.results.slice(0, 4).map((r, i) => (
            <div className="hero-result" key={i}>
              <h4 className="h">{r.h}</h4>
              <div className="snip">{highlight(r.s)}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------- Coverage grid ----------
const COVERAGE = [
  { name: 'Anti-Money Laundering Regulations', desc: '2025 Revision · CDD, monitoring, reporting', status: 'live', query: 'Anti-Money Laundering' },
  { name: 'Beneficial Ownership Transparency Act', desc: '2023 · Reportable particulars + amendments', status: 'live', query: 'Beneficial Ownership' },
  { name: 'Companies Act', desc: '2025 Revision · Director duties, filings', status: 'live', query: 'Companies' },
  { name: 'Mutual Funds Act', desc: '2025 Revision · Registration & audit', status: 'live', query: 'Mutual Funds' },
  { name: 'Private Funds Act', desc: '2025 Revision · Scope & operating rules', status: 'live', query: 'Private Funds' },
  { name: 'Banks and Trust Companies Act', desc: '2025 · Licensing & prudential rules', status: 'live', query: 'Banks' },
  { name: 'Securities Investment Business Act', desc: '2024 Revision · SIBL framework', status: 'live', query: 'Securities' },
  { name: 'Virtual Asset (Service Providers) Act', desc: '2024 Revision · VASP registration', status: 'live', query: 'Virtual Asset' },
  { name: 'CIMA Rules & Statements of Guidance', desc: 'All sector-specific instruments', status: 'live', query: 'CIMA' },
  { name: 'Data Protection Act', desc: '2017 + 2021 Regulations', status: 'soon', query: 'Data Protection' },
  { name: 'Tax Information Authority — CRS / FATCA', desc: 'Reporting framework & guidance', status: 'live', query: 'CRS' },
  { name: 'Insurance Act', desc: 'Long-term, general, and captives', status: 'queue', query: 'Insurance' },
];

function Coverage() {
  return (
    <div className="coverage">
      {COVERAGE.map((c, i) => (
        <a 
          className="cov-item" 
          key={i} 
          href={`https://ditc.caymandesk.com/index.html?q=${encodeURIComponent(c.query)}`}
          target="_blank"
          rel="noopener noreferrer"
        >
          <div className="cov-status">
            <span className={`dot ${c.status}`} />
            {c.status === 'live' ? 'Indexed' : c.status === 'soon' ? 'Q3 2026' : 'Queued'}
          </div>
          <div className="name">{c.name}</div>
          <div className="desc">{c.desc}</div>
        </a>
      ))}
    </div>
  );
}

// ---------- Audit preview mock ----------
function AuditMock() {
  return (
    <div className="audit-mock">
      <div className="audit-head">
        <div className="dots"><i /><i /><i /></div>
        <div className="file">aml-policy-procedure-v4.docx · audit run · 2026-04-29</div>
      </div>
      <div className="audit-body">
        <div className="audit-doc">
          <h5>5. Customer Due Diligence</h5>
          <p>The Firm shall identify and verify the identity of each customer at the commencement of the relationship using <span className="flag">documentary evidence issued by a reliable independent source</span>, and shall maintain such records for a period of five years following the end of the relationship.</p>
          <p>Where the customer is a legal person, the Firm <span className="flag miss">may rely on register extracts</span> in lieu of independent verification of beneficial ownership for entities domiciled in equivalent jurisdictions.</p>
          <p>Enhanced due diligence shall apply to <span className="flag">politically exposed persons</span>, including senior approval prior to onboarding and ongoing enhanced monitoring.</p>
          <h5 style={{ marginTop: 18 }}>6. Suspicious Activity Reporting</h5>
          <p>Internal SARs shall be made to the MLRO without delay. The MLRO shall determine within a reasonable period whether to file a report with the Financial Reporting Authority.</p>
        </div>
        <div className="audit-side">
          <div className="group-title">Findings · 7</div>
          <div className="finding crit">
            <div className="ftitle">§5.2 — Conflicts with AML Reg. 12(1)</div>
            <div className="fmeta">SEVERITY: HIGH · CITATION: AML 2025 §12(1)</div>
            <div className="fbody">Reliance on register extracts is not sufficient verification of beneficial ownership. Regulation requires independent verification regardless of domicile.</div>
          </div>
          <div className="finding">
            <div className="ftitle">§5.1 — Vague evidence standard</div>
            <div className="fmeta">SEVERITY: MED · CITATION: AML 2025 §10(3)(a)</div>
            <div className="fbody">"Reliable independent source" is not defined. Add the four enumerated source categories from §10(3)(a).</div>
          </div>
          <div className="finding">
            <div className="ftitle">§5.3 — PEP definition missing</div>
            <div className="fmeta">SEVERITY: MED · CITATION: AML 2025 §2 (defs)</div>
            <div className="fbody">Section references PEPs but the policy does not adopt the regulatory definition (foreign, domestic, international org).</div>
          </div>
          <div className="finding ok">
            <div className="ftitle">§6.1 — SAR pathway aligned</div>
            <div className="fmeta">PASSED · POCA §136</div>
            <div className="fbody">Internal escalation to MLRO and onward filing matches POCA's required mechanism.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Stats ----------
function Stats() {
  return (
    <div className="stats">
      <div className="stat">
        <div className="num">42</div>
        <span className="lbl">Acts & Regulations Indexed</span>
      </div>
      <div className="stat">
        <div className="num">2,180</div>
        <span className="lbl">Sections & Schedules</span>
      </div>
      <div className="stat">
        <div className="num">14k</div>
        <span className="lbl">Concepts Cross-Linked</span>
      </div>
      <div className="stat">
        <div className="num">24h</div>
        <span className="lbl">Update Window from Gazette</span>
      </div>
    </div>
  );
}

window.Nav = Nav;
window.HeroSearch = HeroSearch;
window.Coverage = Coverage;
window.AuditMock = AuditMock;
window.Stats = Stats;
window.SearchIcon = SearchIcon;
window.ArrowRight = ArrowRight;
