// Parallex marketing site — shared React components
// All components export to window at the bottom.

const { useState, useEffect } = React;

// ────────────────────────────────────────────────────────────
// Primitives
// ────────────────────────────────────────────────────────────

const Eyebrow = ({ children, className = "", style }) => (
  <div className={`px-eyebrow ${className}`} style={style}>{children}</div>
);

const Button = ({ variant = "primary", size = "md", children, onClick, className = "", type = "button" }) => (
  <button type={type} className={`px-btn px-btn-${variant} px-btn-${size} ${className}`} onClick={onClick}>
    {children}
  </button>
);

const Icon = ({ name, size = 20, className = "", style }) => (
  <i data-lucide={name} style={{ width: size, height: size, ...style }} className={className}></i>
);

const SectionHead = ({ eyebrow, title, lede, align = "left" }) => (
  <div className={`px-section-head ${align === "center" ? "px-section-head-center" : ""}`}>
    {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
    <h2 className="px-section-title" dangerouslySetInnerHTML={{ __html: title }} />
    {lede && <p className="px-section-lede">{lede}</p>}
  </div>
);

// ────────────────────────────────────────────────────────────
// Navigation
// ────────────────────────────────────────────────────────────

const NAV_LINKS = [
  { id: "services", label: "Services" },
  { id: "industries", label: "Industries" },
  { id: "work", label: "How we work" },
  { id: "technology", label: "Technology" },
  { id: "contact", label: "Contact" },
];

const Nav = ({ activeRoute, onNavigate }) => (
  <nav className="px-nav">
    <div className="px-nav-inner">
      <a className="px-nav-brand" onClick={() => onNavigate("home")}>
        <img src="./assets/parallex-wordmark.svg" alt="Parallex" height="24"
          style={{ filter: "invert(1)" }} />
      </a>
      <div className="px-nav-links">
        {NAV_LINKS.map(l => (
          <a key={l.id}
             className={`px-nav-link ${activeRoute === l.id ? "active" : ""}`}
             onClick={() => onNavigate(l.id)}>{l.label}</a>
        ))}
      </div>
      <Button variant="accent" size="sm" onClick={() => onNavigate("contact")}>
        Talk to us
      </Button>
    </div>
  </nav>
);

// ────────────────────────────────────────────────────────────
// Hero (Home)
// ────────────────────────────────────────────────────────────

const OrbitalFrame = () => (
  <div className="px-hero-frame" aria-hidden="true">
    <svg viewBox="0 0 400 400" fill="none">
      <defs>
        <linearGradient id="ringGrad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#5DE8FF" stopOpacity="0.9"/>
          <stop offset="50%" stopColor="#A585FF" stopOpacity="0.6"/>
          <stop offset="100%" stopColor="#FF4FD8" stopOpacity="0.3"/>
        </linearGradient>
        <radialGradient id="coreGrad">
          <stop offset="0%" stopColor="#5DE8FF" stopOpacity="0.9"/>
          <stop offset="60%" stopColor="#7C52FF" stopOpacity="0.3"/>
          <stop offset="100%" stopColor="#7C52FF" stopOpacity="0"/>
        </radialGradient>
      </defs>
      {/* outer ring */}
      <g className="ring r3">
        <circle cx="200" cy="200" r="190" stroke="url(#ringGrad)" strokeWidth="1" strokeDasharray="2 6"/>
        <circle cx="200" cy="10"  r="3" fill="#5DE8FF"/>
      </g>
      {/* mid ring, tilted */}
      <g className="ring r2" transform="matrix(1 0 0 0.35 0 130)">
        <circle cx="200" cy="200" r="160" stroke="#5DE8FF" strokeWidth="1" strokeOpacity="0.5"/>
      </g>
      {/* inner ring */}
      <g className="ring">
        <circle cx="200" cy="200" r="120" stroke="#A585FF" strokeWidth="1" strokeOpacity="0.5" strokeDasharray="1 3"/>
        <circle cx="200" cy="80"  r="4" fill="#A585FF"/>
        <circle cx="320" cy="200" r="2" fill="#FF4FD8"/>
      </g>
      {/* parallel bars — the brand mark, living in the core */}
      <g transform="translate(200 200)">
        <circle r="70" fill="url(#coreGrad)"/>
        <rect x="-32" y="-36" width="10" height="72" fill="#5DE8FF" opacity="0.95"/>
        <rect x="-10" y="-36" width="10" height="72" fill="#A585FF" opacity="0.85"/>
        <rect x="12"  y="-36" width="10" height="72" fill="#FF4FD8" opacity="0.75"/>
      </g>
      {/* corner brackets */}
      <g stroke="#5DE8FF" strokeWidth="1.5" fill="none" opacity="0.7">
        <path d="M 10 40 L 10 10 L 40 10"/>
        <path d="M 390 40 L 390 10 L 360 10"/>
        <path d="M 10 360 L 10 390 L 40 390"/>
        <path d="M 390 360 L 390 390 L 360 390"/>
      </g>
    </svg>
  </div>
);

const Hero = ({ onCTA, onSecondary }) => (
  <section className="px-hero">
    <div className="px-container">
      <div className="px-hero-framemark">
        <span>SYS · PARALLEX_AI</span>
        <em>v1.0 / DIMENSION SHIFT</em>
        <em>EST. RUNTIME 2026</em>
      </div>
      <h1 className="px-hero-title">
        Shift your business<br/>
        into a <span className="serif-accent">new dimension.</span>
      </h1>
      <p className="px-hero-sub">
        Parallex runs AI-driven workflows, analytics, and integrations
        inside the systems your team already uses. Same stack. Higher axis.
        Automation that adds capacity — not complexity.
      </p>
      <div className="px-hero-ctas">
        <Button variant="accent" size="lg" onClick={onCTA}>
          Initiate contact <Icon name="arrow-right" size={14} />
        </Button>
        <Button variant="ghost-inverse" size="lg" onClick={onSecondary}>
          See protocol <Icon name="chevron-down" size={14} />
        </Button>
      </div>
      <div className="px-hero-rail">
        <span data-code="PILLAR · 01"><strong>Automation</strong></span>
        <span data-code="PILLAR · 02"><strong>Analysis</strong></span>
        <span data-code="PILLAR · 03"><strong>Integration</strong></span>
        <span data-code="PILLAR · 04"><strong>Operations</strong></span>
      </div>
    </div>
    <OrbitalFrame />
  </section>
);

// Page hero (smaller, for inner pages)
const PageHero = ({ eyebrow, title, lede }) => (
  <section className="px-page-hero">
    <div className="px-container">
      <Eyebrow>{eyebrow}</Eyebrow>
      <h1 className="px-page-hero-title" dangerouslySetInnerHTML={{ __html: title }} />
      {lede && <p className="px-page-hero-lede">{lede}</p>}
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// Pillars
// ────────────────────────────────────────────────────────────

const PILLARS = [
  { num: "01", icon: "workflow", title: "AI workflow automation", slug: "automation",
    body: "Automate support triage, reporting, approvals, and operational workflows inside the systems your team already runs.",
    scope: ["Process identification", "Automation design", "Tool selection or build", "Monitoring and iteration"] },
  { num: "02", icon: "line-chart", title: "Intelligent data analysis", slug: "analysis",
    body: "Use machine learning to surface trends, anomalies, and forecasts — grounded in your data quality and governance.",
    scope: ["Analysis design", "Model or pipeline development", "Visualization and reporting", "Handoff to stakeholders"] },
  { num: "03", icon: "plug", title: "AI integration", slug: "integration",
    body: "APIs, middleware, and event-driven flows that plug AI into the software and stack you're already on.",
    scope: ["API design or consumption", "Middleware", "Event-driven flows", "Security boundaries"] },
  { num: "04", icon: "gauge", title: "Smart business operations", slug: "operations",
    body: "Combine automation with predictive analytics and decision support — always grounded in measurable workflows.",
    scope: ["Operational diagnostics", "Automation prioritization", "Decision support", "Ongoing optimization"] },
];

const Pillars = ({ onNavigate }) => (
  <section className="px-section" id="pillars">
    <div className="px-container">
      <SectionHead
        eyebrow="THE FOUR PILLARS"
        title="Four services.<br/><span class='serif-accent'>One engagement.</span>" />
      <div className="px-pillar-grid">
        {PILLARS.map(p => (
          <article className="px-pillar" key={p.num} onClick={() => onNavigate && onNavigate("services")}>
            <div className="px-pillar-num">{p.num}</div>
            <div className="px-pillar-icon"><Icon name={p.icon} size={22} /></div>
            <h3 className="px-pillar-title">{p.title}</h3>
            <p className="px-pillar-body">{p.body}</p>
            <div className="px-pillar-link">Read more <Icon name="arrow-right" size={14} /></div>
          </article>
        ))}
      </div>
    </div>
  </section>
);

// Detailed services list (Services page)
const ServicesDetail = ({ onContact }) => (
  <section className="px-section">
    <div className="px-container">
      {PILLARS.map((p, i) => (
        <div className="px-service-row" key={p.num} style={{ flexDirection: i % 2 ? "row-reverse" : "row" }}>
          <div className="px-service-meta">
            <div className="px-pillar-num">{p.num} / {p.slug.toUpperCase()}</div>
            <h2 className="px-service-title">{p.title}</h2>
            <p className="px-service-body">{p.body}</p>
            <a className="px-inline-cta" onClick={onContact}>
              Talk to us about {p.slug} <Icon name="arrow-right" size={14} />
            </a>
          </div>
          <div className="px-service-card">
            <div className="px-pillar-icon"><Icon name={p.icon} size={22} /></div>
            <div className="px-service-scope-head">Scope</div>
            <ul className="px-service-scope">
              {p.scope.map(s => <li key={s}><Icon name="check" size={14} /><span>{s}</span></li>)}
            </ul>
          </div>
        </div>
      ))}
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// Industries
// ────────────────────────────────────────────────────────────

const INDUSTRIES = [
  { name: "Healthcare", body: "Operational workflows, documentation support, and analytics — where regulation applies, we work within it.",
    examples: ["Care operations dashboards", "Clinical documentation assistance", "Claims and referral workflows"] },
  { name: "Finance", body: "Reporting automation, risk-related analytics, and compliance-adjacent workflows.",
    examples: ["Reporting automation", "Risk-signal analytics", "KYC workflow support"] },
  { name: "Retail", body: "Demand signals, inventory and ops analytics, and customer-operations automation.",
    examples: ["Demand forecasting", "Inventory health alerts", "Support triage and deflection"] },
  { name: "Manufacturing", body: "Production and quality data, maintenance planning, and supply visibility.",
    examples: ["Production quality analytics", "Predictive maintenance inputs", "Supply-chain visibility"] },
];

const IndustriesTeaser = () => (
  <section className="px-section px-section-dark parallex-dark">
    <div className="px-container">
      <SectionHead
        eyebrow="INDUSTRIES · ILLUSTRATIVE"
        title="Where we've seen this work."
        lede="Reference sectors below are examples, not commitments. Industry-specific claims require verification before we publish them." />
      <div className="px-industry-grid">
        {INDUSTRIES.map((ind, i) => (
          <div className="px-industry" key={ind.name}>
            <div className="px-industry-num">0{i+1}</div>
            <h3 className="px-industry-name">{ind.name}</h3>
            <p className="px-industry-body">{ind.body}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const IndustriesDetail = () => (
  <section className="px-section">
    <div className="px-container">
      {INDUSTRIES.map((ind, i) => (
        <div className="px-industry-row" key={ind.name}>
          <div className="px-industry-row-head">
            <div className="px-industry-num" style={{ color: "var(--fg-muted)" }}>0{i+1}</div>
            <h2 className="px-service-title">{ind.name}</h2>
          </div>
          <div className="px-industry-row-body">
            <p className="px-service-body">{ind.body}</p>
            <div className="px-industry-examples">
              <div className="px-eyebrow" style={{ marginBottom: 10 }}>Example problem areas</div>
              <ul>
                {ind.examples.map(e => <li key={e}><Icon name="arrow-right" size={14} /><span>{e}</span></li>)}
              </ul>
            </div>
          </div>
        </div>
      ))}
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// How we work
// ────────────────────────────────────────────────────────────

const STEPS = [
  { n: "01", t: "Discovery", b: "Map workflows, data, and where AI actually adds value. Identify constraints before we propose anything." },
  { n: "02", t: "Design", b: "Scope the automation, integration points, and measurement. Agree on what 'done' looks like." },
  { n: "03", t: "Build", b: "Implement inside your stack. Instrument everything so outcomes are observable, not assumed." },
  { n: "04", t: "Deploy", b: "Staged rollout with monitoring and guardrails. Humans stay in the loop where judgment matters." },
  { n: "05", t: "Support", b: "Iterate on outcomes as your systems change. Automation is never finished." },
];

const HowWeWork = () => (
  <section className="px-section">
    <div className="px-container">
      <SectionHead
        eyebrow="HOW WE WORK"
        title="Five phases. No surprises."
        lede="Timelines below are examples — your engagement is shaped by your systems, not ours." />
      <div className="px-steps">
        {STEPS.map((s) => (
          <div className="px-step" key={s.n}>
            <div className="px-step-num">{s.n}</div>
            <div className="px-step-line"></div>
            <div className="px-step-body">
              <h4>{s.t}</h4>
              <p>{s.b}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// Technology
// ────────────────────────────────────────────────────────────

const Technology = () => (
  <section className="px-section px-section-light">
    <div className="px-container px-tech">
      <div>
        <Eyebrow>TECHNOLOGY</Eyebrow>
        <h2 className="px-section-title">We're opinionated, not dogmatic.</h2>
        <p className="px-tech-lede">
          Cloud-based infrastructure. ML models chosen per use case.
          Real-time when latency matters. Security and access control that follows your policies.
        </p>
      </div>
      <dl className="px-tech-list">
        <div className="px-tech-row"><dt>Cloud</dt><dd>Scalable managed services where they fit. Deployment model follows your requirements.</dd></div>
        <div className="px-tech-row"><dt>Machine learning</dt><dd>Models and vendors chosen per workload — no single-stack dogma.</dd></div>
        <div className="px-tech-row"><dt>Real-time</dt><dd>Where latency justifies it. Not every use case requires real-time.</dd></div>
        <div className="px-tech-row"><dt>Security</dt><dd>Access control and data handling that follow your policies and applicable law.</dd></div>
      </dl>
    </div>
  </section>
);

// Stack diagram (Technology page)
const StackDiagram = () => (
  <section className="px-section px-section-dark parallex-dark">
    <div className="px-container">
      <SectionHead
        eyebrow="LOGICAL LAYERS"
        title="The shape of an engagement."
        lede="A typical Parallex build has four logical layers. Specific vendors and components are selected per project." />
      <div className="px-stack">
        {[
          { n: "L4", t: "Experience", b: "Dashboards, assistive UI, workflow surfaces. Where humans intervene and decide." },
          { n: "L3", t: "Agents & models", b: "Task-scoped models, retrieval, agents. Chosen per workload, not bet on one stack." },
          { n: "L2", t: "Integration", b: "APIs, middleware, event streams. How AI reaches the systems you already run." },
          { n: "L1", t: "Data foundation", b: "Sources, quality, access control. Nothing above this layer works without it." },
        ].map(l => (
          <div className="px-stack-row" key={l.n}>
            <div className="px-stack-num">{l.n}</div>
            <div className="px-stack-body">
              <h4>{l.t}</h4>
              <p>{l.b}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// Trust — principles, not badges
// ────────────────────────────────────────────────────────────

const Trust = () => (
  <section className="px-section px-section-light">
    <div className="px-container">
      <SectionHead
        eyebrow="TRUST"
        title="Principles over badges."
        lede="We don't list certifications we haven't earned. We commit to the practices we actually follow." />
      <div className="px-trust-grid">
        {[
          { icon: "shield", t: "Security by design", b: "Access control, audit trails, and data handling aligned with your policies and applicable law." },
          { icon: "eye-off", t: "Data minimization", b: "We process only what the workflow requires. Retention is explicit, not incidental." },
          { icon: "git-branch", t: "Versioned change", b: "Models, prompts, and pipelines are versioned. Changes are reviewable and reversible." },
          { icon: "users", t: "Human-in-the-loop", b: "Automation has escape hatches. People stay in the loop wherever judgment matters." },
        ].map(item => (
          <div className="px-trust-item" key={item.t}>
            <div className="px-trust-icon"><Icon name={item.icon} size={20} /></div>
            <h4>{item.t}</h4>
            <p>{item.b}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// CTA band
// ────────────────────────────────────────────────────────────

const CTABand = ({ onContact }) => (
  <section className="px-cta-band parallex-dark">
    <div className="px-container">
      <div className="px-cta-inner">
        <h2 className="px-cta-title">Shift into a <span className="serif-accent">new dimension.</span></h2>
        <p className="px-cta-sub">Tell us what you're trying to automate. We'll respond within two business days.</p>
        <Button variant="accent" size="lg" onClick={onContact}>
          Start a conversation <Icon name="arrow-right" size={16} />
        </Button>
      </div>
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// Contact
// ────────────────────────────────────────────────────────────

const Contact = () => {
  const [state, setState] = useState("idle"); // "idle" | "sending" | "sent" | "error"
  const [errMsg, setErrMsg] = useState("");

  const submit = async (e) => {
    e.preventDefault();
    setState("sending");
    const fd = new FormData(e.target);
    const body = {
      name:    fd.get("name"),
      email:   fd.get("email"),
      company: fd.get("company"),
      message: fd.get("message"),
    };
    try {
      const res = await fetch("/sent-mail.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "Server error");
      }
      setState("sent");
    } catch (err) {
      setErrMsg(err.message || "Something went wrong. Please try again.");
      setState("error");
    }
  };

  return (
    <section className="px-section px-section-dark parallex-dark">
      <div className="px-container px-contact">
        <div>
          <Eyebrow>CONTACT</Eyebrow>
          <h2 className="px-section-title">Start a conversation.</h2>
          <p className="px-contact-lede">
            Tell us what you're trying to automate. We'll respond within two business days.
          </p>
          <div className="px-contact-meta">
            <div><span className="px-eyebrow">EMAIL</span><div>support@parallex.in</div></div>
            <div><span className="px-eyebrow">REGION</span><div>Global · English</div></div>
          </div>
        </div>
        <form className="px-contact-form" onSubmit={submit}>
          {state === "sent" ? (
            <div className="px-contact-success">
              <Icon name="check" size={28} />
              <h3>Message received.</h3>
              <p>Check your inbox — we've sent a confirmation. We'll follow up within two business days.</p>
            </div>
          ) : (
            <>
              <div className="px-f"><label>Full name</label><input name="name" required placeholder="Your name"/></div>
              <div className="px-f"><label>Work email</label><input name="email" type="email" required placeholder="you@company.com"/></div>
              <div className="px-f"><label>Company</label><input name="company" placeholder="Company name"/></div>
              <div className="px-f"><label>What are you trying to automate?</label><textarea name="message" rows="3" placeholder="A short description is enough to start."></textarea></div>
              {state === "error" && (
                <p style={{ color: "#FF4FD8", fontFamily: "var(--font-mono)", fontSize: 12, margin: 0 }}>
                  ⚠ {errMsg}
                </p>
              )}
              <Button variant="accent" size="lg" type="submit" className={state === "sending" ? "px-btn-loading" : ""}>
                {state === "sending" ? "Sending…" : <span>Send message <Icon name="arrow-right" size={16} /></span>}
              </Button>
            </>
          )}
        </form>
      </div>
    </section>
  );
};

// ────────────────────────────────────────────────────────────
// Footer
// ────────────────────────────────────────────────────────────

const Footer = ({ onNavigate }) => (
  <footer className="px-footer parallex-dark">
    <div className="px-container">
      <div className="px-footer-top">
        <div className="px-footer-brand">
          <img src="./assets/parallex-wordmark.svg" alt="Parallex" height="28" style={{filter:"invert(1)"}}/>
          <p>AI automation for businesses. Built inside the systems you already use.</p>
        </div>
        <div className="px-footer-cols">
          <div>
            <h5>Services</h5>
            <a onClick={() => onNavigate("services")}>Automation</a>
            <a onClick={() => onNavigate("services")}>Analysis</a>
            <a onClick={() => onNavigate("services")}>Integration</a>
            <a onClick={() => onNavigate("services")}>Operations</a>
          </div>
          <div>
            <h5>Company</h5>
            <a onClick={() => onNavigate("work")}>How we work</a>
            <a onClick={() => onNavigate("technology")}>Technology</a>
            <a onClick={() => onNavigate("contact")}>Contact</a>
          </div>
          <div>
            <h5>Contact</h5>
            <a href="mailto:support@parallex.in">support@parallex.in</a>
          </div>
        </div>
      </div>
      <div className="px-footer-bottom">
        <span>© 2026 Parallex AI</span>
        <span>Privacy · Terms</span>
      </div>
    </div>
  </footer>
);

Object.assign(window, {
  Eyebrow, Button, Icon, SectionHead,
  Nav, Hero, OrbitalFrame, PageHero,
  Pillars, ServicesDetail,
  IndustriesTeaser, IndustriesDetail,
  HowWeWork, Technology, StackDiagram, Trust,
  CTABand, Contact, Footer,
});
