// components.jsx — shared atoms & molecules
// Exposes Icon, Badge, FreshnessPill, VerifiedBadge, JobRow, Nav, Footer, Toast.

const Icon = ({ name, size = 16, stroke = 1.6, ...rest }) => {
  const s = size;
  const sw = stroke;
  const common = { width: s, height: s, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: sw, strokeLinecap: "round", strokeLinejoin: "round", ...rest };
  const paths = {
    search:    <><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></>,
    location:  <><path d="M12 21s-7-7.5-7-13a7 7 0 0 1 14 0c0 5.5-7 13-7 13Z" /><circle cx="12" cy="8" r="2.5" /></>,
    briefcase: <><rect x="3" y="7" width="18" height="13" rx="2" /><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><path d="M3 12h18" /></>,
    globe:     <><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" /></>,
    check:     <path d="m5 12 5 5L20 7" />,
    cross:     <><path d="M6 6l12 12" /><path d="M18 6 6 18" /></>,
    shield:    <><path d="M12 3 4 6v6c0 5 3.5 8.5 8 9 4.5-.5 8-4 8-9V6l-8-3Z" /><path d="m9 12 2 2 4-4" /></>,
    bookmark:  <path d="M6 4h12v17l-6-4-6 4Z" />,
    plus:      <><path d="M12 5v14" /><path d="M5 12h14" /></>,
    chevron:   <path d="m9 6 6 6-6 6" />,
    user:      <><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></>,
    filter:    <path d="M4 5h16M7 12h10M10 19h4" />,
    bell:      <><path d="M6 8a6 6 0 0 1 12 0c0 7 3 8 3 8H3s3-1 3-8Z" /><path d="M10 21a2 2 0 0 0 4 0" /></>,
    star:      <path d="m12 3 2.7 6 6.3.6-4.8 4.3 1.5 6.1L12 17l-5.7 3 1.5-6.1L3 9.6 9.3 9Z" />,
    edit:      <><path d="M4 20h4l11-11-4-4L4 16Z" /><path d="m13.5 6.5 4 4" /></>,
    trash:     <><path d="M4 7h16" /><path d="M9 7V4h6v3" /><path d="M6 7v13h12V7" /><path d="M10 11v6M14 11v6" /></>,
    refresh:   <><path d="M20 12a8 8 0 1 1-2.5-5.8" /><path d="M20 4v4h-4" /></>,
    flame:     <path d="M12 3s4 3.5 4 8a4 4 0 0 1-8 0 5 5 0 0 1 1.5-3.5C10 6 12 5 12 3Z" />,
    arrowRight:<><path d="M5 12h14" /><path d="m13 5 7 7-7 7" /></>,
    arrowDown: <><path d="M12 5v14" /><path d="m5 13 7 7 7-7" /></>,
    sparkle:   <><path d="M12 3v6" /><path d="M12 15v6" /><path d="M3 12h6" /><path d="M15 12h6" /><path d="m6 6 3 3" /><path d="m15 15 3 3" /><path d="M18 6 15 9" /><path d="M9 15l-3 3" /></>,
    eye:       <><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" /><circle cx="12" cy="12" r="3" /></>,
    eyeOff:    <><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24" /><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68" /><path d="M6.61 6.61A13.52 13.52 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61" /><line x1="2" y1="2" x2="22" y2="22" /></>,

    download:  <><path d="M12 4v12" /><path d="m6 12 6 6 6-6" /><path d="M4 20h16" /></>,
    settings:  <><circle cx="12" cy="12" r="3" /><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" /></>,
    chart:     <><path d="M3 21h18" /><path d="M7 17v-7M12 17V7M17 17v-4" /></>,
    play:      <path d="M7 4v16l13-8Z" />,
    dot:       <circle cx="12" cy="12" r="3" />,
    google:    (
      <g stroke="none" fill="none">
        <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
        <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
        <path d="M5.84 14.1c-.22-.66-.35-1.36-.35-2.1s.13-1.44.35-2.1V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l3.66-2.84z" fill="#FBBC05"/>
        <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z" fill="#EA4335"/>
      </g>
    ),
  };
  return <svg {...common}>{paths[name] || null}</svg>;
};
// ---------- Animated CountUp ----------
const CountUp = ({ end, duration = 2500 }) => {
  const [count, setCount] = React.useState(0);
  const nodeRef = React.useRef(null);
  const hasAnimated = React.useRef(false);

  React.useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !hasAnimated.current) {
        hasAnimated.current = true;
        let startTimestamp = null;
        let req;
        const step = (timestamp) => {
          if (!startTimestamp) startTimestamp = timestamp;
          const progress = Math.min((timestamp - startTimestamp) / duration, 1);
          // Ultra-smooth ease-out exponential curve
          const easeOut = progress === 1 ? 1 : 1 - Math.pow(2, -10 * progress);
          setCount(Math.floor(easeOut * end));
          if (progress < 1) req = window.requestAnimationFrame(step);
        };
        req = window.requestAnimationFrame(step);
      }
    }, { threshold: 0.2 });

    if (nodeRef.current) observer.observe(nodeRef.current);
    return () => observer.disconnect();
  }, [end, duration]);

  return <span ref={nodeRef}>{count.toLocaleString()}</span>;
};

// ---------- Verified Sponsor (animated) ----------
const VerifiedBadge = ({ compact }) => (
  <span className="badge-verified" title="Verified Sponsor — credentials confirmed by GYD">
    <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 1.2 3 5.4v6.3c0 5.4 3.7 9.7 9 11.1 5.3-1.4 9-5.7 9-11.1V5.4l-9-4.2Zm-1.2 14.9-4-4 1.5-1.5 2.5 2.5 5.4-5.4 1.5 1.5-6.9 6.9Z"/>
    </svg>
    {!compact && <span>Verified Sponsor</span>}
  </span>
);

// ---------- Freshness pill ----------
const FreshnessPill = ({ level }) => {
  const labels = { fresh: "Fresh", active: "Active", aging: "Aging" };
  return (
    <span className={`fresh-pill ${level}`}>
      <span className="ring"></span>
      {labels[level]}
    </span>
  );
};

// ---------- Job Row ----------
const JobRow = ({ job, density = "regular", onOpen, onSave, isSaved }) => {
  const country = window.COUNTRIES.find((c) => {
    if (!job.country) return false;
    const jc = job.country.toUpperCase();
    return c.code === jc || jc.includes(c.code) || jc.includes(c.name.toUpperCase());
  });
  const fresh = window.freshnessFromDate(job.verifiedDate);
  const salary = window.fmtSalary(job.salaryMin, job.salaryMax, job.currency);
  const verDays = Math.max(0, Math.floor((Date.now() - new Date(job.verifiedDate).getTime()) / 86400000));

  return (
    <article className={`job-row ${density}`} onClick={() => onOpen?.(job)} role="button">
      <div className={`job-stripe ${fresh}`}></div>
      <div className="job-logo" aria-hidden="true">{job.companyLogo}</div>

      <div className="job-body">
        <div className="job-headline">
          <FreshnessPill level={fresh} />
          {job.visa.verified && <VerifiedBadge />}
          {job.visa.sponsored && <span className="badge badge-navy">{job.visa.type}</span>}
        </div>
        <div className="job-title">{job.title}</div>
        <div className="job-meta">
          <span><b style={{color:"var(--ink-2)", fontWeight: 500}}>{job.company}</b></span>
          <span className="dot"></span>
          <span style={{display:"inline-flex",alignItems:"center",gap:6}}>
            <span className="flag">{country?.flag}</span> {job.city}, {country?.name}
          </span>
          <span className="dot"></span>
          <span style={{display:"inline-flex",alignItems:"center",gap:6}}>
            <Icon name="briefcase" size={13}/> {job.experience}
          </span>
          <span className="dot"></span>
          <span style={{color: job.collar==="white" ? "var(--navy-700)" : "var(--gold-700)", fontWeight: 500, textTransform: "capitalize"}}>{job.collar} collar</span>
        </div>
        <div className="chip-row">
          <span className={`chip ${job.ielts ? "on" : "off"}`}>
            <Icon name={job.ielts ? "check" : "cross"} size={11} />
            IELTS {job.ielts ? "required" : "not required"}
          </span>
          <span className={`chip ${job.pr ? "on" : "off"}`}>
            <Icon name={job.pr ? "check" : "cross"} size={11} />
            PR pathway {job.pr ? "available" : "n/a"}
          </span>
          <span className="chip">
            <Icon name="refresh" size={11} />
            Verified {verDays === 0 ? "today" : verDays === 1 ? "yesterday" : `${verDays}d ago`}
          </span>
        </div>
      </div>

      <div className="job-col">
        <div className="col-label">Salary</div>
        <div className="col-value salary tabular" style={{fontSize: salary === "Not Disclosed" ? "13px" : "15px", whiteSpace: "nowrap"}}>{salary}</div>
        {salary !== "Not Disclosed" && <div className="col-label" style={{marginTop:8}}>per year</div>}
      </div>

      <div className="job-col">
        <div className="col-label">Sponsorship</div>
        <div className="col-value">{job.visa.sponsorshipType}</div>
        <div className="col-label" style={{marginTop:8}}>Industry</div>
        <div className="col-value" style={{fontWeight: 400, color: "var(--ink-3)"}}>{job.industry}</div>
      </div>

      <div className="job-actions" onClick={(e)=>e.stopPropagation()}>
        <button className="btn btn-primary btn-sm" onClick={() => onOpen?.(job)}>Apply
          <Icon name="arrowRight" size={13} />
        </button>
        <button
          className={`btn btn-ghost btn-sm`}
          onClick={() => onSave?.(job)}
          aria-label="Save job"
          style={isSaved ? {background: "var(--navy-50)", borderColor: "var(--navy-100)", color: "var(--navy-800)"} : null}
        >
          <Icon name="bookmark" size={13} />
          {isSaved ? "Saved" : "Save"}
        </button>
      </div>
    </article>
  );
};

// ---------- Top nav ----------
const TopBar = () => (
  <div className="topbar-strip">
    <div className="container">
      <div className="ts-meta">
        <span><span className="live-dot"></span> Live · 6,912 verified sponsored roles open right now</span>
      </div>
      <div className="ts-meta" style={{fontSize: 11}}>
        <span>Markets: <span style={{color:"var(--gold-500)", fontWeight:600}}>DE +18%</span> · <span style={{color:"var(--gold-500)", fontWeight:600}}>CA +9%</span> · <span style={{color:"var(--gold-500)", fontWeight:600}}>AU +12%</span> · <span style={{color:"var(--gold-500)", fontWeight:600}}>AE +7%</span></span>
        <span>EN · IN ₹</span>
      </div>
    </div>
  </div>
);

const Nav = ({ route, setRoute, user, onSignIn, onSignOut, savedCount }) => {
  const [isMobilityMode, setIsMobilityMode] = React.useState(false);

  const handleModeSwitch = (e) => {
    e.stopPropagation();
    if (isMobilityMode) return;
    setIsMobilityMode(true);
    setTimeout(() => {
      window.open("https://www.gyd-mobility.com/", "_blank");
      // Reset after a delay so it's back to default when they return
      setTimeout(() => setIsMobilityMode(false), 1000);
    }, 400);
  };

  const links = [
    { key: "home",   label: "Home" },
    { key: "jobs",   label: "Jobs" },
    { key: "countries", label: "Countries" },
    { key: "saved",  label: <span>Saved {savedCount ? <span style={{marginLeft:6,background:"var(--gold-500)",color:"var(--navy-900)",fontSize:10,fontWeight:700,padding:"1px 6px",borderRadius:10}}>{savedCount}</span> : null}</span> },
  ];
  return (
    <header className="nav">
      <div className="container">
        <div style={{display:"flex", alignItems:"center", gap:20}}>
          <button className="brand" onClick={() => setRoute("home")} style={{background:"transparent", border:0, color:"inherit", padding:0, cursor:"pointer", display:"flex", alignItems:"center", gap:12}}>
            {/* Circle logo */}
            <div className="brand-logo-container">
              <img src="assest/GYD LOGO.png" alt="GYD Career" />
            </div>
            {/* Brand text */}
            <div className="brand-title-group">
              <span className="brand-main">GYD</span>
              <span className="brand-sub">Career</span>
            </div>
          </button>

          <div className="nav-separator"></div>

          {/* Mode Switch Button */}
          <div className="mode-switch-container">
            <div className={`mode-switch ${isMobilityMode ? "active" : ""}`} onClick={handleModeSwitch} title="Switch to GYD Mobility">
              <div className="mode-switch-track">
                <div className="mode-switch-knob"></div>
              </div>
            </div>
            <div className="mode-switch-labels">
              <span className="mode-switch-label">Switch To</span>
              <span className="mode-switch-target">GYD</span>
            </div>
          </div>
        </div>

        <nav className="nav-links">
          {links.map((l) => (
            <button
              key={l.key}
              className={`nav-link ${route === l.key ? "active" : ""}`}
              onClick={() => setRoute(l.key)}
            >{l.label}</button>
          ))}
        </nav>
        <div className="nav-cta">
          {user ? (
            <>
              <div style={{display:"flex",alignItems:"center",gap:8}}>
                <div style={{width:32,height:32,borderRadius:"50%",background:"var(--gold-500)",display:"grid",placeItems:"center",color:"var(--navy-900)",fontWeight:600,fontSize:12}}>
                  {user.name.split(" ").map(n=>n[0]).join("").slice(0,2)}
                </div>
                <div style={{display:"flex",flexDirection:"column",fontSize:12, lineHeight: 1.2}}>
                  <span style={{color:"var(--navy-900)", fontWeight: 600}}>{user.name}</span>
                  <button onClick={onSignOut} style={{background:"none",border:0,color:"var(--ink-3)",padding:0,fontSize:11,textAlign:"left",cursor:"pointer"}}>Sign out</button>
                </div>
              </div>
            </>
          ) : (
            <>
              <button className="btn btn-nav-ghost" onClick={onSignIn}>Sign in</button>
              <button className="btn btn-primary" onClick={onSignIn}>Create account</button>
            </>
          )}
        </div>
      </div>
    </header>
  );
};

// ---------- Footer ----------
const Footer = () => (
  <footer className="footer">
    <div className="container">
      <div className="grid">
        <div>
          <div style={{display:"flex", alignItems:"center", gap:12, marginBottom: 20}}>
            {/* Circle logo — same as header */}
            <div style={{
              width: 52, height: 52,
              borderRadius: "50%",
              background: "var(--white)",
              border: "2px solid var(--gold-400)",
              boxShadow: "0 2px 14px rgba(217,123,77,0.22), inset 0 1px 0 rgba(255,255,255,0.9)",
              display: "flex", alignItems: "center", justifyContent: "center",
              overflow: "hidden",
              flexShrink: 0,
            }}>
              <img src="assest/GYD LOGO.png" alt="GYD Career"
                style={{width: "80%", height: "80%", objectFit: "contain"}} />
            </div>
            {/* Brand text */}
            <div style={{display:"flex", flexDirection:"column", lineHeight: 1}}>
              <span style={{
                fontFamily: "var(--f-display)",
                fontSize: 22,
                fontWeight: 500,
                color: "var(--navy-900)",
                letterSpacing: "0.01em",
              }}>GYD</span>
              <span style={{
                fontSize: 10,
                letterSpacing: "0.22em",
                color: "var(--gold-600)",
                textTransform: "uppercase",
                marginTop: 4,
              }}>Career</span>
            </div>
          </div>
          <p style={{maxWidth: 320, lineHeight: 1.6}}>
            Global mobility intelligence for India's skilled workforce. We verify every sponsor and track every visa pathway, so you don't have to.
          </p>
        </div>
        <div>
          <h6>Platform</h6>
          <ul>
            <li><a href="#">Browse jobs</a></li>
            <li><a href="#">Country guides</a></li>
            <li><a href="#">Visa pathways</a></li>
            <li><a href="#">Salary intelligence</a></li>
          </ul>
        </div>
        <div>
          <h6>For employers</h6>
          <ul>
            <li><a href="#">Post a role</a></li>
            <li><a href="#">Sponsor verification</a></li>
            <li><a href="#">Talent pipeline</a></li>
          </ul>
        </div>
        <div>
          <h6>Trust</h6>
          <ul>
            <li><a href="#">Verification standards</a></li>
            <li><a href="#">Report a scam</a></li>
            <li><a href="#">Compliance</a></li>
          </ul>
        </div>
        <div>
          <h6>Company</h6>
          <ul>
            <li><a href="#">About</a></li>
            <li><a href="#">Press</a></li>
            <li><a href="#">Careers</a></li>
            <li><a href="#">Contact</a></li>
          </ul>
        </div>
      </div>
      <div className="legal">
        <span>© 2026 GYD Global Mobility Pvt Ltd. All rights reserved.</span>
        <span>Privacy · Terms · Cookies</span>
      </div>
    </div>
  </footer>
);

// ---------- Toast ----------
const Toast = ({ msg }) => (
  msg ? (
    <div className="toast-stack">
      <div className="toast"><Icon name="check" size={16} className="check"/> {msg}</div>
    </div>
  ) : null
);

Object.assign(window, { Icon, VerifiedBadge, FreshnessPill, JobRow, Nav, TopBar, Footer, Toast, CountUp });
