// MCP Hero — account settings / profile (role-adaptive: personal / org-admin / org-editor)
const { useState: useProfState } = React;

// Lightweight multiline input, styled to match TextInput
function TextArea({ value, onChange, placeholder, disabled, rows = 2, style = {} }) {
  const [focus, setFocus] = useProfState(false);
  return (
    <textarea
      value={value} placeholder={placeholder} disabled={disabled} rows={rows}
      onChange={(e) => onChange && onChange(e.target.value)}
      onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
      style={{
        padding: '10px 13px', fontSize: 14.5, borderRadius: 9, outline: 'none', width: '100%', resize: 'vertical',
        border: `1.5px solid ${focus ? 'var(--accent)' : 'var(--border-strong)'}`,
        background: disabled ? 'var(--bg-sunken)' : 'var(--bg-raised)', color: disabled ? 'var(--text-3)' : 'var(--text)',
        boxShadow: focus ? '0 0 0 3px color-mix(in oklch, var(--accent) 18%, transparent)' : 'none',
        transition: 'all .15s ease', fontFamily: 'inherit', lineHeight: 1.5, ...style,
      }}
    ></textarea>
  );
}

function PanelCard({ title, sub, badge, children, footer }) {
  return (
    <Card style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14, padding: '18px 22px 0' }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 16.5, fontFamily: 'var(--font-display)', fontWeight: 700 }}>{title}</h3>
          {sub ? <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-3)', lineHeight: 1.5 }}>{sub}</p> : null}
        </div>
        {badge}
      </div>
      <div style={{ padding: '18px 22px' }}>{children}</div>
      {footer ? (
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, alignItems: 'center', padding: '13px 22px', borderTop: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
          {footer}
        </div>
      ) : null}
    </Card>
  );
}

const ROW2 = { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 15 };

// ---------- Profile (personal info) section ----------
function ProfileInfoCard({ acct, role }) {
  const toast = useToast();

  // Use real user data - no mock data
  const init = {
    name: acct.name || 'User',
    email: acct.email || 'user@example.com'
  };

  const [form, setForm] = useProfState(init);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const dirty = form.name !== init.name || form.email !== init.email;

  // Display real account type
  const typeLabel = role === 'personal' ? 'Personal account' :
                   role === 'org-admin' ? `Organization · Admin` :
                   role === 'org-editor' ? `Organization · Editor` :
                   `Organization · ${acct.role || role}`;

  const hue = (acct.name.length * 47) % 360;
  return (
    <PanelCard
      title="Your profile"
      sub="This is how you appear across MCP Hero. Your email is used to sign in."
      footer={<React.Fragment>
        {dirty ? <span style={{ fontSize: 12.5, color: 'var(--text-3)', marginRight: 'auto' }}>Unsaved changes</span> : null}
        <Btn variant="secondary" size="sm" disabled={!dirty} onClick={() => setForm(init)}>Discard</Btn>
        <Btn size="sm" icon="check" disabled={!dirty} onClick={() => { Object.assign(init, form); toast('Profile updated'); }}>Save changes</Btn>
      </React.Fragment>}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 }}>
        <Avatar initials={acct.initials} size={62} hue={hue}></Avatar>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="secondary" size="sm" icon="external" onClick={() => toast('Pick a new photo')}>Change photo</Btn>
            <Btn variant="ghost" size="sm" onClick={() => toast('Photo removed')}>Remove</Btn>
          </div>
          <span style={{ fontSize: 12, color: 'var(--text-3)' }}>JPG or PNG, at least 200×200px.</span>
        </div>
      </div>
      <div style={{ ...ROW2, marginBottom: 15 }}>
        <Field label="Full name"><TextInput value={form.name} onChange={(v) => set('name', v)}></TextInput></Field>
        <Field label="Email" hint="Changing this requires re-verification.">
          <TextInput value={form.email} onChange={(v) => set('email', v)} type="email"></TextInput>
        </Field>
      </div>
      <Field label="Account type">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 13px', borderRadius: 9, background: 'var(--bg-sunken)', border: '1.5px solid var(--border)' }}>
          <Icon name={role === 'personal' ? 'key' : 'users'} size={16} style={{ color: 'var(--text-3)' }}></Icon>
          <span style={{ fontSize: 14, fontWeight: 600 }}>{typeLabel}</span>
          <Badge tone="neutral" style={{ marginLeft: 'auto' }}>Fixed after registration</Badge>
        </div>
      </Field>
    </PanelCard>
  );
}

// ---------- Organization section ----------
function OrgInfoCard({ canEdit }) {
  const toast = useToast();
  const org = MH_ORG_PROFILE;
  const init = {
    legalName: org.legalName, displayName: org.displayName, regNo: org.regNo,
    emailDomain: org.emailDomain, website: org.website, industry: org.industry,
    size: org.size, phone: org.phone, address: org.address,
  };
  const [form, setForm] = useProfState(init);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const dirty = canEdit && Object.keys(init).some((k) => form[k] !== init[k]);
  return (
    <PanelCard
      title="Organization"
      sub={canEdit ? 'Details shown on invoices and used to verify your team.' : 'Managed by your Org Admins.'}
      badge={canEdit ? <Badge tone="accent">Org Admin</Badge> : <Badge tone="neutral">Read-only</Badge>}
      footer={canEdit ? <React.Fragment>
        {dirty ? <span style={{ fontSize: 12.5, color: 'var(--text-3)', marginRight: 'auto' }}>Unsaved changes</span> : null}
        <Btn variant="secondary" size="sm" disabled={!dirty} onClick={() => setForm(init)}>Discard</Btn>
        <Btn size="sm" icon="check" disabled={!dirty} onClick={() => { Object.assign(init, form); toast('Organization details saved'); }}>Save changes</Btn>
      </React.Fragment> : null}
    >
      {!canEdit ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '10px 13px', marginBottom: 18, borderRadius: 10, background: 'var(--warn-bg)', color: 'var(--warn)', fontSize: 12.5, fontWeight: 600 }}>
          <Icon name="shield" size={15}></Icon>
          Only Org Admins can edit organization details. Ask an admin to make changes.
        </div>
      ) : null}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 }}>
        <div style={{
          width: 62, height: 62, borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          background: `linear-gradient(135deg, oklch(0.9 0.06 ${org.hue}), oklch(0.82 0.09 ${org.hue + 30}))`,
          color: `oklch(0.4 0.14 ${org.hue})`, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24,
        }}>{org.initials}</div>
        {canEdit ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Btn variant="secondary" size="sm" icon="external" onClick={() => toast('Pick a company logo')}>Upload logo</Btn>
            <span style={{ fontSize: 12, color: 'var(--text-3)' }}>Square, SVG or PNG. Shown on invoices.</span>
          </div>
        ) : (
          <div>
            <div style={{ fontWeight: 700, fontSize: 16, fontFamily: 'var(--font-display)' }}>{org.displayName}</div>
            <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>{org.legalName}</div>
          </div>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
        <div style={ROW2}>
          <Field label="Legal entity name"><TextInput value={form.legalName} onChange={(v) => set('legalName', v)} disabled={!canEdit}></TextInput></Field>
          <Field label="Display name" hint="Shown in the dashboard and to your team."><TextInput value={form.displayName} onChange={(v) => set('displayName', v)} disabled={!canEdit}></TextInput></Field>
        </div>
        <div style={ROW2}>
          <Field label="SSM registration no."><TextInput value={form.regNo} onChange={(v) => set('regNo', v)} disabled={!canEdit} mono></TextInput></Field>
          <Field label="Official website">
            <TextInput value={form.website} onChange={(v) => set('website', v)} disabled={!canEdit} placeholder="https://"></TextInput>
          </Field>
        </div>
        <Field label="Email domain" hint={form.emailDomain ? 'New members with this domain can be auto-approved to join.' : null}>
          <div style={{ display: 'flex', gap: 9, alignItems: 'center' }}>
            <div style={{ position: 'relative', flex: 1, display: 'flex', alignItems: 'center' }}>
              <span style={{ position: 'absolute', left: 13, fontSize: 14.5, color: 'var(--text-3)', fontWeight: 600, pointerEvents: 'none' }}>@</span>
              <TextInput value={form.emailDomain} onChange={(v) => set('emailDomain', v)} disabled={!canEdit} mono style={{ paddingLeft: 26 }}></TextInput>
            </div>
            {org.domainVerified
              ? <Badge tone="ok"><Icon name="check" size={12}></Icon>Verified</Badge>
              : <Badge tone="warn">Unverified</Badge>}
          </div>
        </Field>
        <div style={ROW2}>
          <Field label="Industry">
            {canEdit
              ? <Select value={form.industry} onChange={(v) => set('industry', v)} options={MH_INDUSTRIES}></Select>
              : <TextInput value={form.industry} disabled></TextInput>}
          </Field>
          <Field label="Company size">
            {canEdit
              ? <Select value={form.size} onChange={(v) => set('size', v)} options={MH_ORG_SIZES.map((s) => ({ value: s, label: s + ' employees' }))}></Select>
              : <TextInput value={form.size + ' employees'} disabled></TextInput>}
          </Field>
        </div>
        <div style={ROW2}>
          <Field label="Phone"><TextInput value={form.phone} onChange={(v) => set('phone', v)} disabled={!canEdit}></TextInput></Field>
          <Field label="Billing address"><TextArea value={form.address} onChange={(v) => set('address', v)} disabled={!canEdit} rows={2}></TextArea></Field>
        </div>
      </div>
    </PanelCard>
  );
}

// ---------- Security section ----------
function SecurityCard() {
  const toast = useToast();
  const [cur, setCur] = useProfState('');
  const [pw, setPw] = useProfState('');
  const [confirm, setConfirm] = useProfState('');
  const ok = pw.length >= 8 && /\d/.test(pw) && pw === confirm && cur.length > 0;
  const mismatch = confirm.length > 0 && pw !== confirm;
  const save = () => { setCur(''); setPw(''); setConfirm(''); toast('Password updated'); };
  return (
    <PanelCard
      title="Password & security"
      sub="Use a strong password you don't reuse anywhere else."
      footer={<Btn size="sm" icon="shield" disabled={!ok} onClick={save}>Update password</Btn>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 15, maxWidth: 420 }}>
        <Field label="Current password"><TextInput value={cur} onChange={setCur} type="password" placeholder="••••••••"></TextInput></Field>
        <Field label="New password"><TextInput value={pw} onChange={setPw} type="password" placeholder="••••••••"></TextInput></Field>
        <PasswordStrength pw={pw}></PasswordStrength>
        <Field label="Confirm new password" hint={mismatch ? null : undefined}>
          <TextInput value={confirm} onChange={setConfirm} type="password" placeholder="••••••••"></TextInput>
          {mismatch ? <span style={{ fontSize: 12.5, color: 'var(--danger)', marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="alert" size={12}></Icon>Passwords don't match</span> : null}
        </Field>
      </div>
    </PanelCard>
  );
}

// ---------- Main ----------
function DashProfile({ user, nav }) {
  // Handle undefined user by providing defaults
  if (!user) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '200px' }}>
        <div style={{ color: 'var(--text-2)', fontSize: 14 }}>Loading user data...</div>
      </div>
    );
  }

  const role = user.role || 'personal';

  // Use REAL user data from the API, not mock data
  const acct = {
    name: user.fullName || user.name || 'User',
    email: user.email || 'user@example.com',
    orgName: user.organizationName || user.orgName || 'Personal Account',
    role: user.role || role || 'personal',
    accountType: user.accountType || (role !== 'personal' ? 'organization' : 'personal')
  };

  const isOrg = role !== 'personal';
  const canEditOrg = role === 'org-admin';

  // Double-check that acct has all required properties before rendering
  if (!acct || !acct.name) {
    console.error('Invalid account object:', acct);
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '200px' }}>
        <div style={{ color: 'var(--text-2)', fontSize: 14 }}>Error loading profile data</div>
      </div>
    );
  }

  return (
    <div className="mh-anim">
      <SectionHead title="Account settings" sub="Manage your profile, organization and sign-in details."></SectionHead>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 760 }}>
        <ProfileInfoCard acct={acct} role={role}></ProfileInfoCard>
        {isOrg ? <OrgInfoCard canEdit={canEditOrg}></OrgInfoCard> : null}
        <SecurityCard></SecurityCard>
      </div>
    </div>
  );
}

Object.assign(window, { DashProfile });
