/* Meridian Onboarding — Shared Components */
const { useState, useEffect, useRef, useCallback } = React;

/* ─── Lucide-style SVG Icons ─── */
function Icon({ name, size = 20, stroke = 1.5, color = "currentColor" }) {
  const paths = {
    arrowRight: "M5 12h14M12 5l7 7-7 7",
    arrowLeft: "M19 12H5M12 19l-7-7 7-7",
    check: "M20 6L9 17l-5-5",
    chevDown: "M6 9l6 6 6-6",
    chevRight: "M9 18l6-6-6-6",
    eye: "M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8zM12 9a3 3 0 100 6 3 3 0 000-6z",
    eyeOff: "M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24M1 1l22 22",
    copy: "M20 9h-9a2 2 0 00-2 2v9a2 2 0 002 2h9a2 2 0 002-2v-9a2 2 0 00-2-2zM5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",
    monitor: "M2 3h20v14H2zM8 21h8M12 17v4",
    globe: "M12 2a10 10 0 100 20 10 10 0 000-20zM2 12h20M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z",
    shield: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",
    creditCard: "M1 4h22v16H1zM1 10h22",
    dollarSign: "M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6",
    building: "M6 22V4a2 2 0 012-2h8a2 2 0 012 2v18M2 22h20M10 6h4M10 10h4M10 14h4M10 18h4",
    x: "M18 6L6 18M6 6l12 12",
    alertCircle: "M12 2a10 10 0 100 20 10 10 0 000-20zM12 8v4M12 16h.01",
    loader: "M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83",
    checkCircle: "M22 11.08V12a10 10 0 11-5.93-9.14M22 4L12 14.01l-3-3",
    lock: "M19 11H5a2 2 0 00-2 2v7a2 2 0 002 2h14a2 2 0 002-2v-7a2 2 0 00-2-2zM7 11V7a5 5 0 0110 0v4",
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
      {(paths[name] || "").split(/(?<=z)/i).filter(Boolean).map((d, i) => <path key={i} d={d} />)}
    </svg>
  );
}

/* ─── Top Header ─── */
function MeridianHeader({ theme }) {
  const R = (typeof window !== "undefined" && window.__resources) || {};
  const logoSrc = theme === "light" ? (R.logoColor || "assets/meridian-horizontal-color.png") : (R.logoLight || "assets/meridian-horizontal-light.png");
  return (
    <header className="m-topbar">
      <img src={logoSrc} alt="Meridian" className="m-topbar-logo" />
      <nav className="m-topbar-nav">
        <a href="#" className="m-topbar-link">How it works</a>
        <a href="#" className="m-topbar-link">Why Meridian</a>
      </nav>
    </header>
  );
}

/* ─── Step Indicator (3 variants) ─── */
function StepIndicator({ current, variant, steps }) {
  const stepList = steps || [
    { num: 1, label: "Authorize" },
    { num: 2, label: "Deposit" },
    { num: 3, label: "Connect MT5" },
  ];
  const pct = ((current) / stepList.length) * 100;

  if (variant === "dots") {
    return (
      <div className="step-dots">
        {stepList.map((s, i) => (
          <div key={i} className="step-dot-group">
            <div className={`step-dot ${i < current ? 'done' : ''} ${i === current ? 'active' : ''}`}></div>
            <span className={`step-dot-label ${i === current ? 'active' : ''}`}>{s.label}</span>
          </div>
        ))}
      </div>
    );
  }
  if (variant === "progress") {
    return (
      <div className="step-progress-wrap">
        <div className="step-progress-bar">
          <div className="step-progress-fill" style={{ width: `${pct}%` }}></div>
        </div>
        <div className="step-progress-labels">
          {stepList.map((s, i) => (
            <span key={i} className={`step-progress-label ${i === current ? 'active' : ''} ${i < current ? 'done' : ''}`}>
              {s.label}
            </span>
          ))}
        </div>
      </div>
    );
  }
  // Default: tabs
  return (
    <div className="step-tabs">
      {stepList.map((s, i) => (
        <div key={i} className={`step-tab ${i < current ? 'done' : ''} ${i === current ? 'active' : ''}`}>
          <span className="step-tab-num">
            {i < current ? <Icon name="check" size={13} stroke={2.5} /> : s.num}
          </span>
          {s.label}
        </div>
      ))}
    </div>
  );
}

/* ─── Accordion ─── */
function Accordion({ title, children, defaultOpen = false }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="m-accordion">
      <button className="m-accordion-trigger" onClick={() => setOpen(!open)}>
        <span>{title}</span>
        <span className={`m-accordion-arrow ${open ? 'open' : ''}`}>
          <Icon name="chevDown" size={18} />
        </span>
      </button>
      {open && <div className="m-accordion-body">{children}</div>}
    </div>
  );
}

/* ─── Copy Field ─── */
function CopyField({ value, label, helper }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = () => {
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <div className="m-input-wrap">
      {label && <label className="m-input-label">{label}</label>}
      <div className="m-copy-field">
        <input className="m-copy-value" value={value} readOnly />
        <button className="m-copy-btn" onClick={handleCopy}>
          {copied ? "Copied" : "Copy"}
        </button>
      </div>
      {helper && <span className="m-input-helper">{helper}</span>}
    </div>
  );
}

/* ─── Password Field ─── */
function PasswordField({ value, label }) {
  const [show, setShow] = useState(false);
  const [copied, setCopied] = useState(false);
  const handleCopy = () => { setCopied(true); setTimeout(() => setCopied(false), 1500); };
  return (
    <div className="m-input-wrap">
      {label && <label className="m-input-label">{label}</label>}
      <div className="m-copy-field">
        <input className="m-copy-value" type={show ? "text" : "password"} value={value} readOnly />
        <button className="m-copy-btn" onClick={() => setShow(!show)} style={{ borderLeft: "1px solid var(--border)", borderRight: "1px solid var(--border)" }}>
          <Icon name={show ? "eyeOff" : "eye"} size={16} />
        </button>
        <button className="m-copy-btn" onClick={handleCopy}>{copied ? "Copied" : "Copy"}</button>
      </div>
    </div>
  );
}

/* ─── Footer ─── */
function MeridianFooter() {
  return (
    <footer className="m-footer">
      <div className="m-footer-grid">
        <div>
          <div className="m-footer-col-title">Product</div>
          <a href="#" className="m-footer-link">How it works</a>
          <a href="#" className="m-footer-link">Why Meridian</a>
          <a href="#" className="m-footer-link">Start trading</a>
        </div>
        <div>
          <div className="m-footer-col-title">Resources</div>
          <a href="#" className="m-footer-link">Help</a>
          <a href="#" className="m-footer-link">Status</a>
          <a href="#" className="m-footer-link">API docs</a>
        </div>
        <div>
          <div className="m-footer-col-title">Company</div>
          <a href="#" className="m-footer-link">About</a>
          <a href="#" className="m-footer-link">Contact</a>
          <a href="#" className="m-footer-link">Telegram</a>
        </div>
        <div>
          <div className="m-footer-col-title">Legal</div>
          <a href="#" className="m-footer-link">Terms</a>
          <a href="#" className="m-footer-link">Privacy</a>
          <a href="#" className="m-footer-link">Risk disclosure</a>
        </div>
      </div>
      <div className="m-footer-disclosure">
        <strong>Risk disclosure.</strong> Trading involves significant risk and you can lose your money. Past performance is not indicative of future results. Meridian does not custody your funds — you are responsible for your account access and the trades you place.
      </div>
      <div className="m-footer-bottom">
        <span>© 2026 Meridian</span>
        <div className="m-footer-socials">
          <a href="#" className="m-footer-link">TG</a>
          <a href="#" className="m-footer-link">X</a>
          <a href="#" className="m-footer-link">Disc</a>
        </div>
      </div>
    </footer>
  );
}

/* ─── Privy-style Signing Modal ─── */
function PrivyModal({ onSign, onClose, state }) {
  // states: "confirm", "signing", "broadcasting", "confirming", "settled"
  const [elapsed, setElapsed] = useState(0);
  useEffect(() => {
    if (state === "signing" || state === "broadcasting" || state === "confirming") {
      const t = setInterval(() => setElapsed(e => e + 1), 1000);
      return () => clearInterval(t);
    } else { setElapsed(0); }
  }, [state]);

  if (state === "settled") {
    return (
      <div className="m-overlay" onClick={onClose}>
        <div className="m-modal" onClick={e => e.stopPropagation()} style={{ textAlign: "center" }}>
          <div style={{ margin: "0 auto var(--space-4)", width: 48, height: 48, borderRadius: "50%", background: "rgba(95,126,120,0.15)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="checkCircle" size={28} color="var(--accent)" />
          </div>
          <h3 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>Authorized</h3>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-6)", lineHeight: 1.6 }}>
            You're all set. Your trading authorization is active, your MetaTrader account is generated, and your money is still in your account.
          </p>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-6)" }}>
            You can revoke this any time from <a href="#">Account</a>.
          </p>
          <button className="m-btn m-btn-dark m-btn-full m-btn-lg" onClick={onClose}>Continue to deposit</button>
          <div style={{ marginTop: "var(--space-3)", fontSize: "var(--text-xs)", color: "var(--fg-subtle)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
            <Icon name="shield" size={12} color="var(--fg-subtle)" /> Protected by Privy
          </div>
        </div>
      </div>
    );
  }

  const stateLabels = {
    signing: "Awaiting signature broadcast.",
    broadcasting: "Broadcasting to network...",
    confirming: "Confirming on-chain..."
  };

  if (state === "signing" || state === "broadcasting" || state === "confirming") {
    return (
      <div className="m-overlay">
        <div className="m-modal" onClick={e => e.stopPropagation()}>
          <h3 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>
            {state === "signing" ? "Signing..." : state === "broadcasting" ? "Broadcasting..." : "Confirming..."}
          </h3>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-5)" }}>
            {stateLabels[state]}
          </p>
          <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)", marginBottom: "var(--space-5)", padding: "var(--space-3) 0", borderTop: "1px solid var(--border)" }}>
            <div className="m-spinner"></div>
            <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Elapsed {elapsed}s</span>
          </div>
          <div style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
            <Icon name="shield" size={12} color="var(--fg-subtle)" /> Protected by Privy
          </div>
        </div>
      </div>
    );
  }

  return null;
}

/* ─── Export everything to window ─── */
Object.assign(window, {
  Icon, MeridianHeader, StepIndicator, Accordion, CopyField, PasswordField,
  MeridianFooter, PrivyModal
});
