// Profile, General (org/project), Cost Analytics, Files, Integrations, SSH Key — lighter screens.

const ProfileScreen = ({ data, setData }) => {
  const [form, setForm] = React.useState(data.profile);
  return (
    <div className="hx-screen">
      <ScreenHeader icon={<IconUser size={20}/>} title="Profile" subtitle="Personal account details and preferences." />
      <Card title="Account">
        <div className="hx-form-row"><Avatar name={form.name} size={64}/><div><div style={{fontWeight:600}}>{form.name}</div><div style={{color:"var(--muted)",fontSize:13}}>{form.email}</div><div style={{marginTop:8}}><Btn kind="secondary" size="sm">Change photo</Btn></div></div></div>
        <FormField label="Full name"><Input value={form.name} onChange={e=>setForm({...form, name:e.target.value})}/></FormField>
        <FormField label="Email"><Input value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></FormField>
        <FormField label="Username" hint="Used in resource paths and the URL of your projects."><Input value={form.username} onChange={e=>setForm({...form, username:e.target.value})}/></FormField>
        <FormField label="Time zone"><Input value={form.tz} onChange={e=>setForm({...form, tz:e.target.value})}/></FormField>
        <div style={{display:"flex",gap:8,marginTop:18}}>
          <Btn kind="primary" onClick={()=>{setData(d=>({...d,profile:form})); window.__toast("Profile saved");}}>Save changes</Btn>
          <Btn kind="secondary" onClick={()=>setForm(data.profile)}>Cancel</Btn>
        </div>
      </Card>
      <Card title="Danger zone" subtitle="Permanent account actions.">
        <DangerZone
          title="Delete account"
          description="Permanently remove your account and all data. This cannot be undone."
          actionLabel="Delete account"
          confirmPhrase="delete my account"
          onConfirm={() => window.__toast("Account deletion requested (demo)")}
        />
      </Card>
      <style>{`
        .hx-form-row { display:flex; gap: 18px; align-items: center; margin-bottom: 22px; }
        .hx-danger-row { display:flex; justify-content:space-between; align-items:center; gap: 16px; }
      `}</style>
    </div>
  );
};

const GeneralOrgScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconBuilding size={20}/>} title="General" subtitle="Organization settings and metadata." />
    <Card title="Organization">
      <FormField label="Organization name"><Input defaultValue={data.org.name}/></FormField>
      <FormField label="Organization ID"><Input defaultValue={data.org.id} readOnly suffix={<IconCopy size={14}/>}/></FormField>
      <FormField label="Industry"><Input defaultValue="Software / AI"/></FormField>
      <FormField label="Country"><Input defaultValue="India"/></FormField>
      <div style={{marginTop:14}}><Btn kind="primary">Save changes</Btn></div>
    </Card>
    <Card title="Usage limits" subtitle="Spend caps and per-project limits for the organization.">
      <div className="hx-limit-grid">
        <LimitRow label="Monthly spend cap" value="$2,500.00" sub="Resets on the 1st of each month."/>
        <LimitRow label="Per-project soft limit" value="$500.00" sub="Warns project members past this threshold."/>
        <LimitRow label="GPU hours / month" value="1,200 hrs" sub="Across all clusters in the org."/>
      </div>
    </Card>
    <style>{`
      .hx-limit-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
    `}</style>
  </div>
);

const LimitRow = ({label,value,sub}) => (
  <div style={{border:"1px solid var(--line)",borderRadius:10,padding:"14px 16px",background:"var(--panel-2)"}}>
    <div style={{color:"var(--muted)",fontSize:12.5,fontWeight:500,letterSpacing:".02em",textTransform:"uppercase"}}>{label}</div>
    <div style={{fontSize:22,fontWeight:600,letterSpacing:"-.01em",marginTop:8,fontFeatureSettings:'"tnum"'}}>{value}</div>
    <div style={{color:"var(--muted)",fontSize:12,marginTop:6}}>{sub}</div>
  </div>
);

const GeneralProjectScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconFolder size={20}/>} title="General" subtitle={`Project settings for ${data.currentProject}.`}/>
    <Card title="Project">
      <FormField label="Project name"><Input defaultValue={data.currentProject}/></FormField>
      <FormField label="Project ID"><Input defaultValue="proj_8e1f3a2c" readOnly suffix={<IconCopy size={14}/>}/></FormField>
      <FormField label="Description"><Input defaultValue="Inference experiments and finetune jobs."/></FormField>
      <FormField label="Default model"><Input defaultValue="helix-7b-instruct"/></FormField>
      <div style={{marginTop:14}}><Btn kind="primary">Save changes</Btn></div>
    </Card>
  </div>
);

const CostAnalyticsScreen = ({ data }) => {
  // Lightweight sparkline + bars
  const days = data.spendByDay;
  const max = Math.max(...days);
  return (
    <div className="hx-screen">
      <ScreenHeader icon={<IconChart size={20}/>} title="Cost Analytics" subtitle="Detailed organization-level spend breakdown." />
      <div className="hx-card-grid hx-3">
        <StatCard label="Total this month"      value={fmt.currency(842.16)}   delta="+18.3%"            deltaTone="warn"/>
        <StatCard label="Forecasted month-end"  value={fmt.currency(1210.40)}  delta="vs $980 last month" deltaTone="neutral"/>
        <StatCard label="Top model"             value="helix-70b"              delta="34% of spend"       deltaTone="accent"/>
      </div>
      <Card title="Spend, last 30 days" action={<Pill tone="neutral">USD</Pill>}>
        <BarChart data={days} formatValue={(v) => fmt.currency(v)} axisLabels={["30d ago", "15d ago", "Today"]}/>
      </Card>
      <Card title="Spend by model">
        <Table
          columns={[
            { key:"model", label:"Model", render:(r)=><span style={{fontFamily:"var(--mono)",fontSize:12.5}}>{r.model}</span> },
            { key:"requests", label:"Requests", w:140, align:"right" },
            { key:"tokens", label:"Tokens", w:160, align:"right" },
            { key:"spend", label:"Spend", w:120, align:"right", render:(r)=>`$${r.spend.toFixed(2)}` },
          ]}
          rows={data.spendByModel}
        />
      </Card>
      <style>{`
        .hx-bars { display: flex; align-items: flex-end; gap: 4px; height: 160px; }
        .hx-bar { flex: 1; background: linear-gradient(to top, var(--accent), color-mix(in oklab, var(--accent) 60%, transparent)); border-radius: 3px 3px 0 0; min-height: 4px; transition: opacity .12s; }
        .hx-bar:hover { opacity: .85; }
      `}</style>
    </div>
  );
};

const StatBlock = ({label,value,delta,tone}) => (
  <Card>
    <div style={{color:"var(--muted)",fontSize:13,fontWeight:500}}>{label}</div>
    <div style={{fontSize:30,fontWeight:600,letterSpacing:"-.02em",marginTop:10,fontFeatureSettings:'"tnum"'}}>{value}</div>
    <div style={{marginTop:8}}><Pill tone={tone}>{delta}</Pill></div>
  </Card>
);

const FilesScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconUpload size={20}/>} title="Files" subtitle="Datasets and artifacts uploaded for finetuning and batch jobs." />
    <Toolbar
      actions={<Btn kind="primary" icon={<IconUpload size={14}/>} onClick={() => window.__nav("upload-file")}>Upload file</Btn>}
      searchPlaceholder="Search files" onSearchChange={() => {}}
    />
    <Card padded={false}>
      <Table
        columns={[
          { key:"name", label:"Name", render:(r)=><span style={{display:"inline-flex",gap:8,alignItems:"center"}}><IconFile size={14}/><span style={{fontWeight:500}}>{r.name}</span></span> },
          { key:"purpose", label:"Purpose", w:160, render:(r)=><Pill tone="neutral">{r.purpose}</Pill> },
          { key:"size", label:"Size", w:110, align:"right" },
          { key:"created", label:"Uploaded", w:160 },
          { key:"action", label:"", w:60, align:"right", render:()=><button className="hx-icon-btn" aria-label="More"><IconMore size={14}/></button> },
        ]}
        rows={data.files}
      />
    </Card>
  </div>
);

const IntegrationsScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconPlug size={20}/>} title="Integrations" subtitle={`Connect ${window.APP_CONFIG.brand.productName} to your existing tools and workflows.`} />
    <div className="hx-int-grid">
      {data.integrations.map(it => (
        <div className="hx-int-card" key={it.name}>
          <div className="hx-int-head">
            <div className="hx-int-logo" style={{background: it.color}}>{it.name[0]}</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:600}}>{it.name}</div>
              <div style={{color:"var(--muted)",fontSize:12.5,marginTop:2}}>{it.desc}</div>
            </div>
            {it.connected ? <Pill tone="good">Connected</Pill> : null}
          </div>
          <div className="hx-int-foot">
            {it.connected
              ? <Btn kind="secondary" size="sm">Manage</Btn>
              : <Btn kind="primary" size="sm">Connect</Btn>}
            <Btn kind="ghost" size="sm" iconRight={<IconExternal size={12}/>}>Docs</Btn>
          </div>
        </div>
      ))}
    </div>
    <style>{`
      .hx-int-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 14px; }
      .hx-int-card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--r-md); padding: 16px; box-shadow: var(--shadow-1); display:flex; flex-direction:column; gap: 14px; }
      .hx-int-head { display:flex; gap: 12px; align-items: flex-start; }
      .hx-int-logo { width: 36px; height: 36px; border-radius: 8px; display:flex; align-items:center; justify-content:center; color: white; font-weight: 700; font-size: 18px; }
      .hx-int-foot { display:flex; gap: 6px; justify-content: space-between; }
    `}</style>
  </div>
);

const SshKeyScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconKey size={20}/>} title="SSH Key" subtitle="Public keys authorized for GPU cluster access." />
    <Toolbar actions={<Btn kind="primary" icon={<IconPlus size={14}/>} onClick={() => window.__nav("new-ssh-key")}>Add SSH key</Btn>}/>
    <Card padded={false}>
      <Table
        columns={[
          { key:"label", label:"Label", render:(r)=><span style={{fontWeight:500}}>{r.label}</span> },
          { key:"fingerprint", label:"Fingerprint", render:(r)=><span style={{fontFamily:"var(--mono)",fontSize:12}}>{r.fp}</span> },
          { key:"added", label:"Added", w:140 },
          { key:"action", label:"", w:60, align:"right", render:()=><button className="hx-icon-btn" aria-label="Remove"><IconTrash size={14}/></button> },
        ]}
        rows={data.sshKeys}
      />
    </Card>
  </div>
);

Object.assign(window, {
  ProfileScreen, GeneralOrgScreen, GeneralProjectScreen,
  CostAnalyticsScreen, FilesScreen, IntegrationsScreen, SshKeyScreen,
});
