// Dashboard — overlays owned by the Accounts card.
//
//   Modal                   shared scrim + card shell
//   AddAccountModal         Figma 7357:122071 — step one of account creation
//   InvestmentAccountsModal Figma 7367:16259  — the "View More" account table
//   Hint                    the dark hover tooltip used by status pills and
//                           the balance-change chip
//
// Loaded before db-app.jsx, so everything here is a plain top-level function
// in the shared script scope, and hooks are reached through `React.` rather
// than destructured — same convention as db-charts.jsx.

/* ---------------- shared shell ---------------- */

function Modal({ title, onClose, width, children }) {
  const card = React.useRef(null);

  // Escape closes; the scrim swallows scroll behind it so the page underneath
  // stays put while the dialog is open.
  React.useEffect(() => {
    const key = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', key);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', key);
      document.body.style.overflow = prev;
    };
  }, [onClose]);

  // Move focus inside on open so the dialog is reachable by keyboard and the
  // first Tab continues within it rather than back out into the page.
  React.useEffect(() => {
    const el = card.current && (card.current.querySelector('.db-iconbtn') || card.current.querySelector('button'));
    if (el) el.focus();
  }, []);

  return (
    <div className="db-scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="db-modal" ref={card} style={{ width }} role="dialog" aria-modal="true" aria-label={title}>
        {children}
      </div>
    </div>
  );
}

function ModalHead({ title, onClose, children }) {
  return (
    <header className="db-modal__head">
      <h2 className="db-modal__title">{title}</h2>
      <div className="db-modal__head-r">
        {children}
        <button type="button" className="db-iconbtn" onClick={onClose} aria-label="Close">
          <Icon name="x" style={{ width: 18, height: 18 }} />
        </button>
      </div>
    </header>
  );
}

/* ---------------- hover tooltip ----------------
   Fixed-positioned rather than absolute: the accounts table scrolls, so an
   absolutely-positioned tip would be clipped by its own row. */

function Hint({ id, anchor, title, rows, align = 'left', compact }) {
  const [pos, setPos] = React.useState(null);

  // Re-measure on scroll and resize: the tip is viewport-fixed, so a scrolling
  // page or accounts table would otherwise leave it stranded where it opened.
  React.useLayoutEffect(() => {
    if (!anchor) return;
    const place = () => {
      const r = anchor.getBoundingClientRect();
      setPos({ top: r.bottom + 6, left: align === 'right' ? r.right : r.left });
    };
    place();
    window.addEventListener('scroll', place, true);
    window.addEventListener('resize', place);
    return () => {
      window.removeEventListener('scroll', place, true);
      window.removeEventListener('resize', place);
    };
  }, [anchor, align]);

  if (!pos) return null;
  return (
    <div
      id={id}
      className={`db-tip db-tip--hover ${align === 'right' ? 'db-tip--r' : ''} ${compact ? 'db-tip--compact' : ''}`}
      style={{ top: pos.top, left: pos.left }}
      role="tooltip"
    >
      {title && <span className="db-tip__title">{title}</span>}
      {rows && rows.map((r, i) => <span className="db-tip__line" key={i}>{r}</span>)}
    </div>
  );
}

// Wraps any inline element in hover/focus tooltip plumbing. The trigger is
// focusable and described by the tip, so the provider detail is reachable
// without a mouse.
function WithHint({ title, rows, align, compact, className = '', children }) {
  const [anchor, setAnchor] = React.useState(null);
  const ref = React.useRef(null);
  const id = React.useId();
  const show = () => setAnchor(ref.current);
  const hide = () => setAnchor(null);
  return (
    <span
      ref={ref}
      className={`db-hinted ${className}`}
      tabIndex={0}
      aria-describedby={anchor ? id : undefined}
      onMouseEnter={show}
      onMouseLeave={hide}
      onFocus={show}
      onBlur={hide}
    >
      {children}
      {anchor && <Hint id={id} anchor={anchor} title={title} rows={rows} align={align} compact={compact} />}
    </span>
  );
}

/* ---------------- 1. Add Account ---------------- */

function AddAccountOption({ opt, onPick }) {
  return (
    <div className={`db-opt ${opt.recommended ? 'is-rec' : ''}`}>
      <div className="db-opt__hd">
        <span className="db-opt__ic"><Icon name={opt.icon} style={{ width: 18, height: 18 }} /></span>
        <h3 className="db-opt__t">{opt.title}</h3>
      </div>
      <p className="db-opt__d">{opt.desc}</p>
      <span className="db-opt__tag">{opt.tag}</span>
      <ul className="db-opt__list">
        {opt.features.map((f, i) => (
          <li className="db-opt__li" key={i}>
            <Icon name="check" style={{ width: 18, height: 18 }} />
            {f}
          </li>
        ))}
      </ul>
      <button
        type="button"
        className={`db-cta ${opt.recommended ? 'db-cta--primary' : ''}`}
        onClick={() => onPick(opt.key)}
      >
        {opt.cta}
      </button>
    </div>
  );
}

function AddAccountModal({ onClose }) {
  const a = DB.addAccount;
  // Step two (the manual form / the Yodlee handoff) is not designed yet, so the
  // prototype acknowledges the choice and closes rather than dead-ending.
  const pick = (key) => {
    console.info(`[prototype] Add Account — chose "${key}"; step two is not designed yet.`);
    onClose();
  };

  return (
    <Modal title="Add Account" onClose={onClose} width={706}>
      <ModalHead title="Add Account" onClose={onClose} />
      <div className="db-modal__body db-addacct">
        <div className="db-addacct__opts">
          {a.options.map((o) => <AddAccountOption key={o.key} opt={o} onPick={pick} />)}
        </div>
        <div className="db-note">
          <span className="db-note__ic"><Icon name={a.security.icon} style={{ width: 18, height: 18 }} /></span>
          <span className="db-note__txt">
            <span className="db-note__t">{a.security.title}</span>
            <span className="db-note__d">{a.security.desc}</span>
          </span>
          <LinkOut>{a.security.link}</LinkOut>
        </div>
      </div>
    </Modal>
  );
}

/* ---------------- 2. Investment Accounts table ---------------- */

const DB_ACCOUNT_COLS = [
  { key: 'name', label: 'Account Name', grow: true },
  { key: 'owner', label: 'Owner', width: 140 },
  { key: 'rate', label: 'Return', width: 140, right: true },
  { key: 'balance', label: 'Current Balance', width: 204, right: true },
  { key: 'contribution', label: 'Annual Contribution', width: 180, right: true },
  { key: 'edit', label: '', width: 96, right: true },
];

function InvestmentAccountsModal({ onClose, onAdd }) {
  const rows = DB.accounts.rows;
  return (
    <Modal title="Investment Accounts" onClose={onClose} width={1200}>
      <ModalHead title="Investment Accounts" onClose={onClose}>
        <button type="button" className="db-addlink" onClick={onAdd}>
          <Icon name="plus" style={{ width: 15, height: 15 }} />
          Add Account
        </button>
        <span className="db-btn__sep" />
      </ModalHead>

      <div className="db-modal__body db-acctable">
        <div className="db-acctable__head">
          {DB_ACCOUNT_COLS.map((c) => (
            <span
              key={c.key}
              className={`db-acctable__h ${c.right ? 'is-right' : ''}`}
              style={c.grow ? undefined : { width: c.width }}
            >
              {c.label}
            </span>
          ))}
        </div>

        <div className="db-acctable__body">
          {rows.map((r, i) => (
            <div className="db-acctable__row" key={i}>
              <span className="db-acctable__ic"><Icon name={r.icon} style={{ width: 18, height: 18 }} /></span>

              <span className="db-acctable__c db-acctable__c--name">
                <span className="db-acctable__nm">{r.name}</span>
                <span className="db-acctable__sub">{r.desc}</span>
              </span>

              <span className="db-acctable__c db-acctable__c--owner" style={{ width: 140 }}>
                <Icon name="circle-user-round" style={{ width: 18, height: 18 }} />
                <span className="db-acctable__owner">{r.owner}</span>
              </span>

              <span className="db-acctable__c is-right is-muted tabular" style={{ width: 140 }}>
                {r.rate.toFixed(2)}%
              </span>

              <span className="db-acctable__c is-right db-acctable__bal" style={{ width: 204 }}>
                <span className="tabular">{DB.money(r.balance)}</span>
                <WithHint align="right" compact title={`${r.change} since ${DB.accounts.changeSince}`}>
                  <span className="db-chip tabular">{r.change}</span>
                </WithHint>
              </span>

              <span className="db-acctable__c is-right is-muted tabular" style={{ width: 180 }}>
                +{DB.money(r.contribution)}/year
              </span>

              <span className="db-acctable__c is-right" style={{ width: 96 }}>
                <button type="button" className="db-editbtn">
                  <Icon name="square-pen" style={{ width: 14, height: 14 }} />
                  Edit
                </button>
              </span>
            </div>
          ))}
        </div>
      </div>
    </Modal>
  );
}
