// Shared screen primitives + modals. Entry-point: loaded after ui.jsx, before app.jsx.
// Also loads the screen modules.

const ScreenHeader = ({ icon, title, subtitle, right }) => (
  <header className="hx-sh">
    <div className="hx-sh-left">
      <div className="hx-sh-title">{icon}<h1>{title}</h1></div>
      {subtitle && <div className="hx-sh-sub">{subtitle}</div>}
    </div>
    {right}
    <style>{`
      .hx-sh { display:flex; justify-content: space-between; align-items: flex-start; gap: 16px; }
      .hx-sh-title { display:flex; align-items: center; gap: 10px; color: var(--ink); }
      .hx-sh-title h1 { font-size: 24px; font-weight: 600; margin: 0; letter-spacing: -.015em; }
      .hx-sh-sub { color: var(--muted); font-size: 14px; margin-top: 6px; max-width: 720px; }
    `}</style>
  </header>
);

const Banner = ({ tone = "info", icon, children }) => (
  <div className={`hx-banner hx-banner-${tone}`}>
    <span className="hx-banner-icon">{icon}</span>
    <span className="hx-banner-text">{children}</span>
    <style>{`
      .hx-banner { display:flex; gap: 10px; align-items: flex-start; padding: 12px 14px; border-radius: 10px; font-size: 13.5px; line-height: 1.55; }
      .hx-banner-info { background: var(--info-soft); color: var(--info-ink); }
      .hx-banner-warn { background: var(--warn-soft); color: var(--warn); }
      .hx-banner-icon { display:inline-flex; flex-shrink: 0; margin-top: 1px; }
    `}</style>
  </div>
);

const Table = ({ columns, rows }) => (
  <div className="hx-table-wrap">
    <table className="hx-table">
      <thead>
        <tr>
          {columns.map(c => (
            <th key={c.key} style={{ width: c.w, textAlign: c.align || "left" }}>{c.label}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.length === 0 ? (
          <tr><td colSpan={columns.length} className="hx-table-empty">No results.</td></tr>
        ) : rows.map((r, i) => (
          <tr key={r.id || i}>
            {columns.map(c => (
              <td key={c.key} style={{ textAlign: c.align || "left", fontFamily: c.mono ? "var(--mono)" : undefined, fontSize: c.mono ? 12.5 : undefined }}>
                {c.render ? c.render(r) : r[c.key]}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
    <style>{`
      .hx-table-wrap { overflow-x: auto; max-width: 100%; }
      .hx-table { width: 100%; min-width: 560px; border-collapse: collapse; font-size: 13.5px; }
      .hx-table thead th {
        text-align: left; padding: 12px 16px;
        color: var(--muted); font-weight: 500; font-size: 12.5px;
        letter-spacing: .02em;
        background: var(--panel-2); border-bottom: 1px solid var(--line);
      }
      .hx-table thead th:first-child { border-top-left-radius: var(--r-md); }
      .hx-table thead th:last-child { border-top-right-radius: var(--r-md); }
      .hx-table tbody td { padding: 14px 16px; border-bottom: 1px solid var(--line-2); color: var(--ink-2); vertical-align: middle; }
      .hx-table tbody tr:last-child td { border-bottom: none; }
      .hx-table tbody tr:hover { background: var(--hover); }
      .hx-table-empty { text-align: center; color: var(--muted); padding: 40px !important; }
    `}</style>
  </div>
);

const FormField = ({ label, hint, children }) => (
  <div className="hx-ff">
    <label className="hx-ff-label">{label}</label>
    <div className="hx-ff-control">{children}</div>
    {hint && <div className="hx-ff-hint">{hint}</div>}
    <style>{`
      .hx-ff { margin-bottom: 14px; }
      .hx-ff-label { display:block; font-size: 13px; font-weight: 500; color: var(--ink-2); margin-bottom: 6px; }
      .hx-ff-hint { font-size: 12px; color: var(--muted); margin-top: 4px; }
      .hx-ff-control > .hx-input-wrap { width: 100%; }
    `}</style>
  </div>
);

// =============== MODALS ===============
const AddCreditsModal = ({ open, onClose, onConfirm }) => {
  const presets = [10, 25, 50, 100, 250];
  const [amt, setAmt] = React.useState(25);
  return (
    <Modal open={open} onClose={onClose} title="Add credits" width={460}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" onClick={() => { onConfirm(amt); onClose(); }}>Add ${amt}</Btn>
      </>}>
      <p style={{margin:"0 0 14px", color:"var(--muted)", fontSize:13.5}}>Credits are charged to your saved payment method. They never expire.</p>
      <div className="hx-amt-grid">
        {presets.map(p => (
          <button key={p} className={`hx-amt ${amt === p ? "on" : ""}`} onClick={() => setAmt(p)}>${p}</button>
        ))}
      </div>
      <FormField label="Custom amount">
        <Input prefix="$" type="number" value={amt} onChange={e=>setAmt(Number(e.target.value)||0)} />
      </FormField>
      <style>{`
        .hx-amt-grid { display:grid; grid-template-columns: repeat(5, 1fr); gap: 8px; margin-bottom: 16px; }
        .hx-amt { padding: 12px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); cursor: pointer; font: inherit; color: var(--ink); font-weight: 500; transition: all .12s ease; }
        .hx-amt:hover { border-color: var(--accent); }
        .hx-amt.on { background: var(--accent-soft); border-color: var(--accent); color: var(--accent-strong); }
      `}</style>
    </Modal>
  );
};

const AddProjectModal = ({ open, onClose, onConfirm }) => {
  const [name, setName] = React.useState("");
  const [desc, setDesc] = React.useState("");
  return (
    <Modal open={open} onClose={onClose} title="New project" width={480}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" disabled={!name} onClick={() => { onConfirm({ name, desc }); onClose(); setName(""); setDesc(""); }}>Create project</Btn>
      </>}>
      <FormField label="Project name"><Input value={name} onChange={e=>setName(e.target.value)} placeholder="my-new-project"/></FormField>
      <FormField label="Description (optional)"><Input value={desc} onChange={e=>setDesc(e.target.value)} placeholder="What is this project for?"/></FormField>
    </Modal>
  );
};

const InviteMemberModal = ({ open, onClose, onConfirm }) => {
  const [email, setEmail] = React.useState("");
  const [role, setRole] = React.useState("Member");
  return (
    <Modal open={open} onClose={onClose} title="Invite member" width={460}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" disabled={!email} onClick={() => { onConfirm({ email, role }); onClose(); setEmail(""); }}>Send invite</Btn>
      </>}>
      <FormField label="Email"><Input value={email} onChange={e=>setEmail(e.target.value)} placeholder="teammate@example.com" type="email"/></FormField>
      <FormField label="Role">
        <div className="hx-role-grid">
          {["Member","Admin","Owner"].map(r=>(
            <button key={r} className={`hx-amt ${role===r?"on":""}`} onClick={()=>setRole(r)}>{r}</button>
          ))}
        </div>
      </FormField>
      <style>{`.hx-role-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;}`}</style>
    </Modal>
  );
};

const EditAddressModal = ({ open, onClose, value, onConfirm }) => {
  const [v, setV] = React.useState(value || "");
  React.useEffect(()=>setV(value||""), [value, open]);
  return (
    <Modal open={open} onClose={onClose} title="Edit invoice address" width={480}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" onClick={() => { onConfirm(v); onClose(); }}>Save</Btn>
      </>}>
      <FormField label="Address" hint="Shown on invoices and used for tax calculations.">
        <textarea className="hx-ta" value={v} onChange={e=>setV(e.target.value)} rows={5}/>
      </FormField>
      <style>{`
        .hx-ta { width: 100%; font: inherit; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; resize: vertical; background: var(--panel); color: var(--ink); }
        .hx-ta:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 18%, transparent); }
      `}</style>
    </Modal>
  );
};

const EditPaymentModal = ({ open, onClose, onConfirm }) => (
  <Modal open={open} onClose={onClose} title="Update payment method" width={460}
    footer={<>
      <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
      <Btn kind="primary" onClick={() => { onConfirm(); onClose(); }}>Save card</Btn>
    </>}>
    <FormField label="Card number"><Input placeholder="•••• •••• •••• ••••" /></FormField>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
      <FormField label="Expiry"><Input placeholder="MM / YY"/></FormField>
      <FormField label="CVC"><Input placeholder="•••"/></FormField>
    </div>
    <FormField label="Name on card"><Input placeholder="Full name"/></FormField>
  </Modal>
);

const EditTaxModal = ({ open, onClose, onConfirm }) => {
  const [type, setType] = React.useState("GSTIN");
  const [val, setVal] = React.useState("");
  return (
    <Modal open={open} onClose={onClose} title="Tax ID" width={460}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" onClick={() => { onConfirm({ type, val }); onClose(); }} disabled={!val}>Save</Btn>
      </>}>
      <FormField label="Tax ID type">
        <div style={{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:8}}>
          {["GSTIN","VAT","EIN","ABN"].map(t=>(
            <button key={t} className={`hx-amt ${type===t?"on":""}`} onClick={()=>setType(t)}>{t}</button>
          ))}
        </div>
      </FormField>
      <FormField label="ID number"><Input value={val} onChange={e=>setVal(e.target.value)} placeholder={type==="GSTIN" ? "22AAAAA0000A1Z5" : "1234567890"}/></FormField>
    </Modal>
  );
};

const CreateKeyModal = ({ open, onClose, onConfirm }) => {
  const [name, setName] = React.useState("");
  const [project, setProject] = React.useState("Default Project");
  return (
    <Modal open={open} onClose={onClose} title="Create API key" width={460}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" disabled={!name} onClick={()=>{onConfirm({name, project}); onClose(); setName("");}}>Create key</Btn>
      </>}>
      <FormField label="Name" hint="A descriptive label for this key (e.g. 'prod-server')."><Input value={name} onChange={e=>setName(e.target.value)} placeholder="key name"/></FormField>
      <FormField label="Project"><Input value={project} onChange={e=>setProject(e.target.value)}/></FormField>
    </Modal>
  );
};

const AutoRechargeModal = ({ open, onClose, value, onConfirm }) => {
  const [threshold, setThreshold] = React.useState(value?.threshold || 5);
  const [amount, setAmount] = React.useState(value?.amount || 25);
  React.useEffect(()=>{ if(value){ setThreshold(value.threshold); setAmount(value.amount); }}, [value, open]);
  return (
    <Modal open={open} onClose={onClose} title="Auto-recharge thresholds" width={460}
      footer={<>
        <Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" onClick={()=>{onConfirm({threshold, amount}); onClose();}}>Save thresholds</Btn>
      </>}>
      <FormField label="Trigger auto-recharge when balance falls below">
        <Input prefix="$" type="number" value={threshold} onChange={e=>setThreshold(Number(e.target.value)||0)}/>
      </FormField>
      <FormField label="Recharge by">
        <Input prefix="$" type="number" value={amount} onChange={e=>setAmount(Number(e.target.value)||0)}/>
      </FormField>
    </Modal>
  );
};

Object.assign(window, {
  ScreenHeader, Banner, Table, FormField,
  AddCreditsModal, AddProjectModal, InviteMemberModal, EditAddressModal,
  EditPaymentModal, EditTaxModal, CreateKeyModal, AutoRechargeModal,
});
