// LegalModal.jsx — Overlay modal displaying Privacy Policy and Terms of Service.
// Listens for the global `af:show-legal` event.

const { useState, useEffect } = React;

function LegalModal() {
  const [open, setOpen] = useState(false);
  const [tab, setTab] = useState("privacy"); // "privacy" or "terms"

  useEffect(() => {
    const onShow = (e) => {
      const type = e?.detail?.type || "privacy";
      setTab(type);
      setOpen(true);
    };
    window.addEventListener("af:show-legal", onShow);
    return () => window.removeEventListener("af:show-legal", onShow);
  }, []);

  // Esc to close, lock body scroll while open.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  // Re-run Lucide icons when the active tab or modal open state changes
  useEffect(() => {
    if (open && window.lucide) {
      window.lucide.createIcons();
    }
  }, [open, tab]);

  if (!open) return null;

  const activeTabStyle = {
    flex: 1,
    padding: "12px 16px",
    background: "var(--blue-50)",
    color: "var(--blue)",
    border: "none",
    borderBottom: "2px solid var(--blue)",
    fontFamily: "var(--font-sans)",
    fontSize: "15px",
    fontWeight: 700,
    cursor: "pointer",
    textAlign: "center",
    transition: "all 0.15s ease",
  };

  const inactiveTabStyle = {
    flex: 1,
    padding: "12px 16px",
    background: "transparent",
    color: "var(--ink-soft)",
    border: "none",
    borderBottom: "2px solid var(--line-2)",
    fontFamily: "var(--font-sans)",
    fontSize: "15px",
    fontWeight: 500,
    cursor: "pointer",
    textAlign: "center",
    transition: "all 0.15s ease",
  };

  const sectionHeadingStyle = {
    fontSize: "18px",
    fontWeight: 700,
    color: "var(--ink)",
    marginTop: "24px",
    marginBottom: "12px",
    fontFamily: "var(--font-sans)",
  };

  const paragraphStyle = {
    fontSize: "15px",
    lineHeight: "1.6",
    color: "var(--ink-soft)",
    marginBottom: "16px",
    fontFamily: "var(--font-sans)",
  };

  const listStyle = {
    paddingLeft: "20px",
    marginBottom: "16px",
    color: "var(--ink-soft)",
    fontSize: "15px",
    lineHeight: "1.6",
  };

  const listItemStyle = {
    marginBottom: "8px",
  };

  return (
    <div onClick={() => setOpen(false)} style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(12, 46, 80, 0.6)",
      backdropFilter: "blur(8px)",
      WebkitBackdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: "24px 20px",
      overflowY: "auto",
      animation: "afmodal-fade .18s ease-out",
    }}>
      <style>{`
        @keyframes afmodal-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes afmodal-pop  { from { transform: translateY(12px) scale(.98); opacity: 0; } to { transform: none; opacity: 1; } }
        
        .legal-modal-card::-webkit-scrollbar {
          width: 8px;
        }
        .legal-modal-card::-webkit-scrollbar-track {
          background: transparent;
        }
        .legal-modal-card::-webkit-scrollbar-thumb {
          background: var(--line);
          border-radius: 4px;
        }
        .legal-modal-card::-webkit-scrollbar-thumb:hover {
          background: var(--muted-2);
        }
      `}</style>
      
      <div onClick={(e) => e.stopPropagation()} style={{
        position: "relative",
        width: "100%", maxWidth: 680,
        height: "85vh", maxHeight: 720,
        background: "#fff", borderRadius: 20,
        boxShadow: "0 30px 80px rgba(0,0,0,0.3), 0 0 0 1px rgba(0,0,0,0.05)",
        animation: "afmodal-pop .25s cubic-bezier(.2,.8,.2,1)",
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
      }}>
        {/* Header tabs */}
        <div style={{ display: "flex", width: "100%", borderBottom: "1px solid var(--line)" }}>
          <button 
            onClick={() => setTab("privacy")} 
            style={tab === "privacy" ? activeTabStyle : inactiveTabStyle}
            onMouseEnter={e => { if (tab !== "privacy") e.currentTarget.style.color = "var(--ink)"; }}
            onMouseLeave={e => { if (tab !== "privacy") e.currentTarget.style.color = "var(--ink-soft)"; }}
          >
            Privacy Policy
          </button>
          <button 
            onClick={() => setTab("terms")} 
            style={tab === "terms" ? activeTabStyle : inactiveTabStyle}
            onMouseEnter={e => { if (tab !== "terms") e.currentTarget.style.color = "var(--ink)"; }}
            onMouseLeave={e => { if (tab !== "terms") e.currentTarget.style.color = "var(--ink-soft)"; }}
          >
            Terms of Service
          </button>
          
          {/* Close button spacer */}
          <div style={{ width: "60px", borderBottom: "2px solid var(--line-2)" }}></div>
        </div>

        {/* Floating Close Button */}
        <button onClick={() => setOpen(false)} aria-label="Close" style={{
          position: "absolute", top: 8, right: 12, zIndex: 10,
          width: 36, height: 36, borderRadius: 10,
          background: "rgba(0,0,0,0.04)", border: "1px solid var(--line)",
          color: "var(--ink-soft)", cursor: "pointer",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          transition: "background .15s, color .15s, transform .12s",
        }}
          onMouseEnter={e => { e.currentTarget.style.background = "rgba(0,0,0,0.08)"; e.currentTarget.style.color = "var(--ink)"; }}
          onMouseLeave={e => { e.currentTarget.style.background = "rgba(0,0,0,0.04)"; e.currentTarget.style.color = "var(--ink-soft)"; }}>
          <i data-lucide="x" style={{ width: 18, height: 18, strokeWidth: 2.25 }}></i>
        </button>

        {/* Modal content body (scrollable) */}
        <div className="legal-modal-card" style={{
          flex: 1,
          overflowY: "auto",
          padding: "36px 36px 40px",
        }}>
          {tab === "privacy" ? (
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: "8px" }}>
                <span style={{
                  padding: "4px 8px", background: "var(--blue-50)", color: "var(--blue)",
                  borderRadius: 6, fontSize: "11px", fontWeight: 700, fontFamily: "var(--font-mono)",
                  textTransform: "uppercase", letterSpacing: "0.05em"
                }}>GDPR Compliant</span>
                <span style={{ fontSize: "13px", color: "var(--muted)", fontFamily: "var(--font-mono)" }}>Last updated: May 2026</span>
              </div>
              <h1 style={{ fontSize: "28px", fontWeight: 800, color: "var(--ink)", marginBottom: "20px", fontFamily: "var(--font-sans)", letterSpacing: "-0.02em" }}>
                Privacy Policy
              </h1>
              
              <p style={paragraphStyle}>
                Welcome to AI Fitters, operated by <strong>AI HEROES LIMITED</strong> (“we”, “our”, or “us”). We are dedicated to protecting your privacy and ensuring your personal data is handled securely and in compliance with applicable laws, including the UK GDPR and the Data Protection Act 2018.
              </p>
              
              <h2 style={sectionHeadingStyle}>1. Introduction</h2>
              <p style={paragraphStyle}>
                This Privacy Policy explains how we collect, use, disclose, and safeguard your personal data when you visit our website, contact us through our contact form, or communicate with us via social channels such as WhatsApp and Telegram.
              </p>

              <h2 style={sectionHeadingStyle}>2. Personal Data We Collect</h2>
              <p style={paragraphStyle}>
                We may collect and process the following categories of personal data:
              </p>
              <ul style={listStyle}>
                <li style={listItemStyle}><strong>Contact Information:</strong> Your name, phone number, email address, and messaging handles (WhatsApp or Telegram) provided voluntarily when filling out our contact form or messaging us directly.</li>
                <li style={listItemStyle}><strong>Usage & Technical Data:</strong> Your IP address, browser type, operating system, pages visited, time spent, and referral sources, collected via cookies or web server logs.</li>
                <li style={listItemStyle}><strong>Communications History:</strong> Contents of your inquiries, requests for project fittings, and correspondence with our team.</li>
              </ul>

              <h2 style={sectionHeadingStyle}>3. How We Use Your Data</h2>
              <p style={paragraphStyle}>
                We only process your personal data when we have a lawful basis to do so. These purposes include:
              </p>
              <ul style={listStyle}>
                <li style={listItemStyle}>To provide, operate, and improve our services and consulting.</li>
                <li style={listItemStyle}>To respond to your inquiries, schedule consultation sessions, and fit AI tools to your business.</li>
                <li style={listItemStyle}>To maintain the security and integrity of our systems.</li>
                <li style={listItemStyle}>To comply with legal, regulatory, or tax obligations in the United Kingdom.</li>
              </ul>

              <h2 style={sectionHeadingStyle}>4. Data Sharing & Third Parties</h2>
              <p style={paragraphStyle}>
                We do not sell, trade, or rent your personal data to third parties. We may share limited personal information with trusted service providers who help us run our business:
              </p>
              <ul style={listStyle}>
                <li style={listItemStyle}>Hosting providers and form-processing backends (e.g., our secure n8n automation platform).</li>
                <li style={listItemStyle}>Messaging services like WhatsApp and Telegram for direct support communication.</li>
                <li style={listItemStyle}>Professional advisors, auditors, or law enforcement bodies if required by UK law.</li>
              </ul>

              <h2 style={sectionHeadingStyle}>5. Data Retention & Security</h2>
              <p style={paragraphStyle}>
                We store your personal data only as long as necessary to fulfill the purposes for which it was collected or to satisfy legal requirements. We employ robust physical, administrative, and technical security safeguards (such as SSL encryption, firewalls, and strict access controls) to prevent unauthorized access or disclosure.
              </p>

              <h2 style={sectionHeadingStyle}>6. Your Rights</h2>
              <p style={paragraphStyle}>
                Under the UK GDPR, you have the following rights regarding your personal data:
              </p>
              <ul style={listStyle}>
                <li style={listItemStyle}>The right to access the personal data we hold about you.</li>
                <li style={listItemStyle}>The right to request the correction of inaccurate personal data.</li>
                <li style={listItemStyle}>The right to request erasure of your data under specific conditions ("right to be forgotten").</li>
                <li style={listItemStyle}>The right to restrict or object to the processing of your personal data.</li>
                <li style={listItemStyle}>The right to data portability.</li>
              </ul>
              <p style={paragraphStyle}>
                To exercise any of these rights, please contact our privacy compliance team at <a href="mailto:team@aiheroes.co.uk" style={{ color: "var(--blue)", textDecoration: "none", fontWeight: 600 }}>team@aiheroes.co.uk</a>.
              </p>

              <h2 style={sectionHeadingStyle}>7. Contact Us</h2>
              <p style={paragraphStyle}>
                If you have questions about this Privacy Policy, or our handling of your data, you can reach us at:
              </p>
              <div style={{
                background: "var(--sand)", borderRadius: 12, padding: "16px 20px", border: "1px solid var(--line)",
                fontFamily: "var(--font-sans)", fontSize: "14px", color: "var(--ink-soft)"
              }}>
                <strong>AI HEROES LIMITED</strong><br />
                Company Number: 14106402<br />
                62 White Lodge Close, London, TW7 6TH<br />
                Email: <a href="mailto:team@aiheroes.co.uk" style={{ color: "var(--blue)", textDecoration: "none" }}>team@aiheroes.co.uk</a>
              </div>
            </div>
          ) : (
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: "8px" }}>
                <span style={{
                  padding: "4px 8px", background: "var(--blue-50)", color: "var(--blue)",
                  borderRadius: 6, fontSize: "11px", fontWeight: 700, fontFamily: "var(--font-mono)",
                  textTransform: "uppercase", letterSpacing: "0.05em"
                }}>Agreement</span>
                <span style={{ fontSize: "13px", color: "var(--muted)", fontFamily: "var(--font-mono)" }}>Last updated: May 2026</span>
              </div>
              <h1 style={{ fontSize: "28px", fontWeight: 800, color: "var(--ink)", marginBottom: "20px", fontFamily: "var(--font-sans)", letterSpacing: "-0.02em" }}>
                Terms of Service
              </h1>
              
              <p style={paragraphStyle}>
                These Terms of Service govern your use of the website and services offered by AI Fitters, a trading name of <strong>AI HEROES LIMITED</strong>. By accessing our site, requesting a consultation, or engaging with our service channels, you agree to these Terms.
              </p>

              <h2 style={sectionHeadingStyle}>1. Professional Scope of Services</h2>
              <p style={paragraphStyle}>
                AI Fitters specializes in artificial intelligence integrations, consulting, custom workflow automation setups, and digital tools fitting. The contents of this website represent our general capabilities.
              </p>
              <p style={paragraphStyle}>
                Any specific engineering or consulting engagement requires a separate, mutually signed Agreement, Service Order, or Statement of Work (SOW) detailing deliverables, milestones, payment schedules, and performance specifications.
              </p>

              <h2 style={sectionHeadingStyle}>2. Intellectual Property Rights</h2>
              <p style={paragraphStyle}>
                All materials, designs, visual assets, copywriting, code examples, software architecture descriptions, and graphics on this website are the intellectual property of <strong>AI HEROES LIMITED</strong> unless otherwise specified.
              </p>
              <p style={paragraphStyle}>
                You are granted a limited, revocable, non-exclusive license to browse this site for informational purposes. You may not copy, frame, scrape, modify, distribute, or reverse-engineer any portion of the site without explicit written authorization from us.
              </p>

              <h2 style={sectionHeadingStyle}>3. Communication Channels</h2>
              <p style={paragraphStyle}>
                We facilitate communication via web forms, email, WhatsApp, and Telegram. By initiating contact:
              </p>
              <ul style={listStyle}>
                <li style={listItemStyle}>You agree that all information provided is accurate and truthful.</li>
                <li style={listItemStyle}>You represent that you have the authority to request consultations on behalf of your business entity.</li>
                <li style={listItemStyle}>You must not submit malicious files, scripts, or offensive language.</li>
              </ul>

              <h2 style={sectionHeadingStyle}>4. Disclaimer of Warranties</h2>
              <p style={paragraphStyle}>
                This website and its general resources are provided on an "as is" and "as available" basis without any express or implied warranties. While we strive to present accurate, up-to-date case studies and tools descriptions, we do not guarantee the website will be uninterrupted or error-free.
              </p>

              <h2 style={sectionHeadingStyle}>5. Limitation of Liability</h2>
              <p style={paragraphStyle}>
                To the maximum extent permitted under the laws of England and Wales, <strong>AI HEROES LIMITED</strong> (including its directors, employees, and affiliates) shall not be liable for any direct, indirect, incidental, special, consequential, or punitive damages. This includes, without limitation, loss of profits, data loss, business interruption, or any other commercial damages arising out of your access to, use of, or reliance upon the informational content of this website.
              </p>

              <h2 style={sectionHeadingStyle}>6. Governing Law & Jurisdiction</h2>
              <p style={paragraphStyle}>
                These Terms of Service and any dispute, claim, or controversy arising out of or in connection with them (including non-contractual disputes) shall be governed by, and construed in accordance with, the laws of England and Wales. Both parties submit to the exclusive jurisdiction of the English courts.
              </p>

              <h2 style={sectionHeadingStyle}>7. Contacting Us</h2>
              <p style={paragraphStyle}>
                If you have questions or concerns regarding these Terms, please reach out to us at:
              </p>
              <div style={{
                background: "var(--sand)", borderRadius: 12, padding: "16px 20px", border: "1px solid var(--line)",
                fontFamily: "var(--font-sans)", fontSize: "14px", color: "var(--ink-soft)"
              }}>
                <strong>AI HEROES LIMITED</strong><br />
                Company Number: 14106402<br />
                Registered Address: 62 White Lodge Close, London, TW7 6TH<br />
                Email: <a href="mailto:team@aiheroes.co.uk" style={{ color: "var(--blue)", textDecoration: "none" }}>team@aiheroes.co.uk</a>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.LegalModal = LegalModal;
