/* Dulius App UI Kit - Profile */

const BUSINESS_PROFILE_KEY = "dulius:business-profile:v1";

function getStoredBusinessProfile() {
  try { return JSON.parse(localStorage.getItem(BUSINESS_PROFILE_KEY) || "null") || {}; }
  catch (e) { return {}; }
}

function businessProfileDefaults() {
  const nameParts = (DULIUS.user.name || "").trim().split(/\s+/);
  return {
    ownerName: DULIUS.user.name || "",
    email: "",
    phone: "",
    businessName: DULIUS.user.business || "",
    legalName: DULIUS.user.business ? DULIUS.user.business + " LLC" : "",
    entity: "LLC",
    industry: DULIUS.user.industry || "",
    founded: "Jan 2024",
    revenue: "$18,400",
    employees: "9",
    ein: "** *** 7741",
    website: "",
    address: "",
    city: "",
    state: "",
    zip: "",
    firstName: nameParts[0] || "",
    lastName: nameParts.slice(1).join(" ") || "",
  };
}

function normalizeBusinessProfile(profile) {
  const base = businessProfileDefaults();
  const merged = { ...base, ...profile };
  if (!merged.ownerName) merged.ownerName = [merged.firstName, merged.lastName].filter(Boolean).join(" ");
  if (!merged.firstName || !merged.lastName) {
    const parts = (merged.ownerName || "").trim().split(/\s+/);
    merged.firstName = merged.firstName || parts[0] || "";
    merged.lastName = merged.lastName || parts.slice(1).join(" ") || "";
  }
  return merged;
}

function profileInitials(name) {
  return (name || "").split(/\s+/).map((p) => p[0]).join("").slice(0, 2).toUpperCase();
}

function saveBusinessProfile(profile) {
  if (window.duliusSaveProfile) { try { window.duliusSaveProfile(profile); } catch (e) {} }
  const next = normalizeBusinessProfile(profile);
  localStorage.setItem(BUSINESS_PROFILE_KEY, JSON.stringify(next));
  if (window.applyDuliusProfile) {
    window.applyDuliusProfile({ ownerName: next.ownerName, businessName: next.businessName, industry: next.industry, initials: profileInitials(next.ownerName) }, "profile");
  }
  window.dispatchEvent(new CustomEvent("dulius:business-profile-saved", { detail: next }));
  return next;
}

function Profile({ onNav, onApplyFunding }) {
  const [autosync, setAutosync] = React.useState(true);
  const [softpull, setSoftpull] = React.useState(true);
  const [contact, setContact] = React.useState(false);
  const [editing, setEditing] = React.useState(false);
  const [savedAt, setSavedAt] = React.useState("");
  const [profile, setProfile] = React.useState(() => normalizeBusinessProfile(getStoredBusinessProfile()));
  const setField = (key, value) => setProfile((current) => ({ ...current, [key]: value }));
  const save = () => {
    const next = saveBusinessProfile(profile);
    setProfile(next);
    setEditing(false);
    setSavedAt("Saved just now");
  };

  const checklist = [
    { id: "biz", label: "Business details", done: !!(profile.businessName && profile.industry && profile.revenue), status: profile.businessName ? "Ready for application pre-fill" : "Missing business name", pts: null },
    { id: "owner", label: "Owner contact", done: !!(profile.ownerName && profile.email && profile.phone), status: profile.email ? "Contact details saved" : "Add email and phone", pts: 15, cta: "Edit profile", icon: "user" },
    { id: "bank", label: "Connect your business bank", done: false, status: "Not connected", pts: 180, cta: "Connect bank", icon: "landmark" },
    { id: "id", label: "Government-issued ID", done: false, status: "Missing", pts: 0, cta: "Upload ID", icon: "id-card", note: "Required before funding" },
    { id: "tax", label: "Tax returns (last 2 yrs)", done: false, status: "Not uploaded", pts: 25, cta: "Upload", icon: "file-text" },
  ];
  const doneCount = checklist.filter((c) => c.done).length;
  const pct = Math.round((doneCount / checklist.length) * 100);
  const potential = checklist.filter((c) => !c.done).reduce((s, c) => s + (c.pts || 0), 0);
  const detailRows = [
    ["Legal name", profile.legalName || profile.businessName],
    ["EIN", profile.ein || "Not added"],
    ["Industry", profile.industry || "Not added"],
    ["Founded", profile.founded || "Not added"],
    ["Monthly revenue", profile.revenue || "Not added"],
    ["Employees", profile.employees || "Not added"],
  ];

  return (
    <div className="dscreen">
      <Card className="dprofhero">
        <Avatar initials={profileInitials(profile.ownerName) || DULIUS.user.initials} size={72} />
        <div className="dprofhero-txt">
          <div className="dprofhero-name">{profile.ownerName || DULIUS.user.name}</div>
          <div className="dprofhero-biz">{profile.businessName || DULIUS.user.business}</div>
          <div className="dprofhero-badges">
            <Badge tone="success" dot>Dulius {DULIUS.user.plan}</Badge>
            <Badge tone="warning" dot>Profile {pct}% complete</Badge>
            <ScorePill band={DULIUS.score.band} />
            {savedAt && <Badge tone="success" dot>{savedAt}</Badge>}
          </div>
        </div>
        <Button variant="accent" icon="file-plus" onClick={onApplyFunding}>Apply for funding</Button>
      </Card>

      <Card className="dcomplete">
        <div className="dcomplete-head">
          <div>
            <div className="ds-overline">Complete your profile</div>
            <div className="dcomplete-sub">A complete profile means a more accurate score and a faster application. You're <strong>{pct}% there</strong> - finishing could add up to <strong className="dnum">+{potential} points</strong>.</div>
          </div>
          <div className="dcomplete-ring dnum" style={{ "--p": pct }}><span>{pct}%</span></div>
        </div>
        <div className="dcomplete-bar"><span style={{ width: pct + "%" }} /></div>
        <div className="dcomplete-list">
          {checklist.map((c) => (
            <div key={c.id} className={("dcomplete-item " + (c.done ? "done" : "")).trim()}>
              <span className={"dcomplete-check " + (c.done ? "on" : "")}>{c.done ? <Icon name="check" size={13} /> : <Icon name={c.icon || "circle"} size={15} />}</span>
              <div className="dcomplete-txt">
                <div className="dcomplete-label">{c.label}{c.note && !c.done && <span className="dcomplete-flag">{c.note}</span>}</div>
                <div className="dcomplete-status">{c.status}{!c.done && c.pts ? " - up to +" + c.pts + " pts" : ""}</div>
              </div>
              {c.done
                ? <Badge tone="success" dot>Done</Badge>
                : <Button variant={c.id === "bank" ? "accent" : "ghost"} size="sm" iconRight="arrow-right" onClick={() => c.id === "owner" ? setEditing(true) : null}>{c.cta}</Button>}
            </div>
          ))}
        </div>
      </Card>

      <div className="dgrid-2">
        <Card className="dpanel">
          <div className="dpanel-head"><h3 className="ds-h3">Business profile</h3><button className="dlink" onClick={() => setEditing(!editing)}>{editing ? "Cancel" : "Edit"}</button></div>
          {!editing ? (
            <div className="dfields">{detailRows.map(([k, v], i) => <div key={i} className="dfield-row"><span className="dfield-k">{k}</span><span className="dfield-v dnum">{v}</span></div>)}</div>
          ) : (
            <div className="afa-grid">
              <AField label="First name"><input className="afa-in" value={profile.firstName || ""} onChange={(e) => setProfile((c) => ({ ...c, firstName: e.target.value, ownerName: (e.target.value + " " + (c.lastName || "")).trim() }))} /></AField>
              <AField label="Last name"><input className="afa-in" value={profile.lastName || ""} onChange={(e) => setProfile((c) => ({ ...c, lastName: e.target.value, ownerName: ((c.firstName || "") + " " + e.target.value).trim() }))} /></AField>
              <AField label="Email"><input className="afa-in" value={profile.email} onChange={(e) => setField("email", e.target.value)} /></AField>
              <AField label="Phone"><input className="afa-in" value={profile.phone} onChange={(e) => setField("phone", e.target.value)} /></AField>
              <AField label="Business name"><input className="afa-in" value={profile.businessName} onChange={(e) => setField("businessName", e.target.value)} /></AField>
              <AField label="Legal name"><input className="afa-in" value={profile.legalName} onChange={(e) => setField("legalName", e.target.value)} /></AField>
              <AField label="Entity type"><input className="afa-in" value={profile.entity} onChange={(e) => setField("entity", e.target.value)} /></AField>
              <AField label="Industry"><input className="afa-in" value={profile.industry} onChange={(e) => setField("industry", e.target.value)} /></AField>
              <AField label="Monthly revenue"><input className="afa-in" value={profile.revenue} onChange={(e) => setField("revenue", e.target.value)} /></AField>
              <AField label="Employees"><input className="afa-in" value={profile.employees} onChange={(e) => setField("employees", e.target.value)} /></AField>
              <AField label="EIN"><input className="afa-in" value={profile.ein} onChange={(e) => setField("ein", e.target.value)} /></AField>
              <AField label="Website" full><input className="afa-in" value={profile.website} onChange={(e) => setField("website", e.target.value)} /></AField>
              <AField label="Business address" full><input className="afa-in" value={profile.address} onChange={(e) => setField("address", e.target.value)} /></AField>
              <AField label="City"><input className="afa-in" value={profile.city} onChange={(e) => setField("city", e.target.value)} /></AField>
              <AField label="State"><input className="afa-in" value={profile.state} onChange={(e) => setField("state", e.target.value)} /></AField>
              <AField label="ZIP"><input className="afa-in" value={profile.zip} onChange={(e) => setField("zip", e.target.value)} /></AField>
              <div className="full"><Button variant="accent" icon="save" onClick={save}>Save profile</Button></div>
            </div>
          )}
        </Card>

        <div className="dstack">
          <Card className="dpanel">
            <div className="dpanel-head"><h3 className="ds-h3">Application readiness</h3><button className="dlink" onClick={onApplyFunding}>Start application</button></div>
            <div className="dlinked">
              <div className="dlinked-row"><span className="dlinked-logo"><Icon name="building-2" size={16} /></span><div className="dlinked-txt"><div className="dlinked-name">Business profile</div><div className="dlinked-sub">Saved details pre-fill the funding application</div></div><Badge tone="success" dot>Ready</Badge></div>
              <div className="dlinked-row missing"><span className="dlinked-logo missing"><Icon name="landmark" size={16} /></span><div className="dlinked-txt"><div className="dlinked-name">Business bank</div><div className="dlinked-sub">Not connected - funders can still review your first pass</div></div><Button variant="accent" size="sm" iconRight="arrow-right">Connect</Button></div>
              <div className="dlinked-row missing"><span className="dlinked-logo missing"><Icon name="id-card" size={16} /></span><div className="dlinked-txt"><div className="dlinked-name">Government ID</div><div className="dlinked-sub">Needed before funding is finalized</div></div><Button variant="ghost" size="sm">Upload</Button></div>
            </div>
          </Card>

          <Card className="dpanel">
            <div className="dpanel-head"><h3 className="ds-h3">Preferences</h3></div>
            <div className="dprefs">
              <Toggle label="Auto-sync bank feed" sub="Refresh balances daily for live scoring" on={autosync} onToggle={() => setAutosync(!autosync)} />
              <Toggle label="Soft-pull offer matching" sub="Find offers without affecting your score" on={softpull} onToggle={() => setSoftpull(!softpull)} />
            </div>
          </Card>
        </div>
      </div>

      {contact && (
        <div className="dmodal-scrim" onClick={() => setContact(false)}>
          <div className="dmodal wide" onClick={(e) => e.stopPropagation()}>
            <div className="dmodal-icon"><Icon name="mail" size={24} /></div>
            <h3 className="dmodal-t">Ask us to update your profile</h3>
            <p className="dmodal-s">Need to change something our team verifies? Send a note and we will review it.</p>
            <label className="dcardf full" style={{ marginBottom: 12 }}><span>What should we update?</span><textarea className="dtextarea" rows={3} placeholder="e.g. My monthly revenue is now $24,000." /></label>
            <Button variant="accent" style={{ width: "100%" }} iconRight="send" onClick={() => setContact(false)}>Send request</Button>
            <button className="dmodal-cancel" onClick={() => setContact(false)}>Cancel</button>
          </div>
        </div>
      )}
    </div>
  );
}

function Toggle({ label, sub, on, onToggle }) {
  return (
    <div className="dtoggle-row">
      <div><div className="dtoggle-label">{label}</div>{sub && <div className="dtoggle-sub">{sub}</div>}</div>
      <button className={"dtoggle " + (on ? "on" : "")} onClick={onToggle} aria-pressed={on}><span className="dtoggle-knob" /></button>
    </div>
  );
}
Object.assign(window, { Profile, Toggle, getStoredBusinessProfile, saveBusinessProfile });
