<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:vm="using:DodoSSH.Client.Shell.ViewModels"
             xmlns:contracts="using:DodoSSH.Contracts"
             x:Class="DodoSSH.Client.App.Views.VaultsScreen"
             x:DataType="vm:VaultsViewModel">

  <!--
    Vaults, and the people in each of them.

    ── THIS WAS THE TEAMS SCREEN, AND THE TEAM IS NOW BEHIND THE VAULT. ─────────────────────────────────
    The left column used to list teams; a team owned vaults, and sharing meant creating a team, then a
    vault in it, then wrapping a key. Two of those three steps were about a concept nobody came here for.
    So the rows are vaults now: naming one makes the membership list that carries it, and everything on
    the right — members, key holders — is that vault's. The server still authorises against
    a team, because that is what VaultAccessService resolves; what went is the requirement that a person
    know it exists. The one case where it is still visible is a membership list carrying several vaults,
    which this screen cannot make and will not hide: see SharedMembershipWarning.

    ── THE ONE FACT THE WHOLE SCREEN IS BUILT AROUND ────────────────────────────────────────────────────
    Adding somebody to a vault and giving them its key are two different acts, and only the first is
    something a server can do. The second needs a machine that holds the key, because this server never
    does. So the members list and the key-holders list are both here and are not the same list, an
    addition says out loud that it granted nothing readable yet, and SHARE KEY is its own button rather
    than a checkbox on the member row.

    What the design asked for and is still not here: two-factor state (no such concept exists anywhere in
    this product) and avatars (no picture is stored anywhere). There is no INVITED list either, and that
    one is a decision rather than a gap — an address is not a way into a vault, so only an account that
    already exists can be added and there is nothing pending to draw. See the ADD box below, which says
    what to do about somebody who has not signed in here yet. Last-active is recorded at most once per
    account per hour, so it is drawn coarsely. Nor is there a way to delete a vault: the server has no
    such call, and the screen says so rather than offering a button that refuses.
  -->

  <Grid ColumnDefinitions="268,*">

    <!-- ============ The vault list ============ -->
    <Border Grid.Column="0" BorderBrush="{StaticResource Border}" BorderThickness="0,0,1,0">
      <Grid RowDefinitions="44,*,Auto">

        <Border Grid.Row="0" Padding="14,0" BorderBrush="{StaticResource Border}" BorderThickness="0,0,0,1">
          <Grid ColumnDefinitions="*,Auto" VerticalAlignment="Center">
            <TextBlock Grid.Column="0" Classes="mono" Text="VAULTS" FontSize="12" FontWeight="SemiBold"
                       LetterSpacing="1" Foreground="{StaticResource Text}" VerticalAlignment="Center" />
            <Button Grid.Column="1" Classes="ghost" Content="NEW"
                    Command="{Binding NewVaultCommand}" IsEnabled="{Binding !IsBusy}"
                    ToolTip.Tip="Makes a vault you can share. Its key is generated on this machine, and nobody else has it until you hand it out." />
          </Grid>
        </Border>

        <ScrollViewer Grid.Row="1">
          <StackPanel>
            <!--
              Read from this machine's own vault list rather than from the server, so the column is right
              with no connection. What is missing offline is who is in each one, which is why a row can
              say its membership is unknown rather than saying nothing at all.
            -->
            <ListBox ItemsSource="{Binding Vaults}" SelectedItem="{Binding SelectedVault}"
                     Background="Transparent" BorderThickness="0">
              <ListBox.ItemTemplate>
                <DataTemplate x:DataType="vm:VaultRowViewModel">
                  <StackPanel Spacing="2" Margin="0,3">
                    <Grid ColumnDefinitions="*,Auto">
                      <TextBlock Grid.Column="0" Text="{Binding Name}" FontSize="13" FontWeight="Medium"
                                 Foreground="{StaticResource Text}" TextTrimming="CharacterEllipsis" />
                      <TextBlock Grid.Column="1" Classes="mono" Text="{Binding RoleLabel}" FontSize="10"
                                 Foreground="{StaticResource TextFaint}" VerticalAlignment="Center"
                                 Margin="8,0,0,0" />
                    </Grid>
                    <TextBlock Classes="hint" FontSize="11" Text="{Binding Detail}" />
                    <!--
                      Only when there is something to say. A vault waiting for a key and one owing a rekey
                      are both temporary and both need somebody to act; a permanent "fine" beside them
                      would teach people to stop reading the line.
                    -->
                    <TextBlock Classes="hint" FontSize="10.5" Text="{Binding State}"
                               TextWrapping="Wrap" IsVisible="{Binding HasState}" />
                  </StackPanel>
                </DataTemplate>
              </ListBox.ItemTemplate>
            </ListBox>

            <TextBlock Classes="hint" FontSize="11" Margin="14,12" TextWrapping="Wrap"
                       IsVisible="{Binding !HasVaults}"
                       Text="No vaults yet. Unlock your keychain to see the personal one, or make a vault to share hosts and credentials with colleagues." />
          </StackPanel>
        </ScrollViewer>

        <!--
          The name-a-vault form, in place rather than in a modal: this window has no idiom for one. It is
          in this column rather than beside the pane on the right for one reason — that pane is bound to
          HasSelection, so with no vaults at all it is not on screen, and "no vaults at all" is exactly
          the state somebody arrives in from the tab strip's New vault entry.

          One field. The membership list behind it is made with it and named after it, and its slug is
          derived — see VaultsViewModel.CreateVaultAsync. Asking for a URL handle would be asking for one
          from somebody who has not been told they are making anything but a vault.
        -->
        <Border Grid.Row="2" Padding="14,12" BorderBrush="{StaticResource Border}" BorderThickness="0,1,0,0"
                IsVisible="{Binding IsCreatingVault}">
          <StackPanel Spacing="8">
            <TextBlock Classes="label" Text="NEW VAULT" />
            <TextBox PlaceholderText="Name" Text="{Binding NewVaultName}" />
            <TextBlock Classes="hint" FontSize="10.5" TextWrapping="Wrap"
                       Text="Its key is made on this machine and nobody else has it. Add people to it once it exists, then press SHARE KEY." />
            <StackPanel Orientation="Horizontal" Spacing="6">
              <Button Classes="accent" Content="CREATE" Command="{Binding CreateVaultCommand}"
                      IsEnabled="{Binding !IsBusy}" />
              <Button Classes="ghost" Content="CANCEL" Command="{Binding CancelNewVaultCommand}" />
            </StackPanel>
          </StackPanel>
        </Border>

      </Grid>
    </Border>

    <!-- ============ The selected vault: who is in it, and who can open it ============ -->
    <Grid Grid.Column="1" RowDefinitions="44,*,Auto">

      <Border Grid.Row="0" Padding="14,0" BorderBrush="{StaticResource Border}" BorderThickness="0,0,0,1">
        <Grid ColumnDefinitions="*,Auto" VerticalAlignment="Center">
          <TextBlock Grid.Column="0" Classes="mono" Text="{Binding SelectedVault.Name}" FontSize="12"
                     FontWeight="SemiBold" LetterSpacing="1" Foreground="{StaticResource Text}"
                     VerticalAlignment="Center" />

          <!--
            The vault's own operations. RENAME is an admin's; handing it on is the owner's alone, and
            that is the line the server draws as well — an admin the owner promoted must not be able to
            take the vault from them.

            DELETE is an admin's too, and it is last and red because it is the only one of the three that
            cannot be undone. It is absent on the personal vault rather than disabled: there is no version
            of this window in which that vault can go, so a greyed button would be an offer that never
            becomes real. Its question is the card below, as every destructive answer on this screen is.
          -->
          <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="6"
                      IsVisible="{Binding ShowsVaultActions}">
            <Button Classes="ghost" Content="RENAME" Command="{Binding RenameVaultCommand}"
                    IsEnabled="{Binding !IsBusy}" IsVisible="{Binding CanAdministerSelected}"
                    ToolTip.Tip="Changes what this vault is called. The name is plaintext on the server, as it always was; nothing inside is re-encrypted." />
            <Button Classes="ghost" Content="HAND OVER" Command="{Binding HandOverCommand}"
                    IsEnabled="{Binding !IsBusy}" IsVisible="{Binding OwnsSelected}"
                    ToolTip.Tip="Hands this vault to the selected member. They become its owner and you become an admin; only the new owner can hand it on again." />
            <Button Classes="danger" Content="DELETE" Command="{Binding DeleteVaultCommand}"
                    IsEnabled="{Binding !IsBusy}" IsVisible="{Binding CanDeleteSelected}"
                    ToolTip.Tip="Deletes this vault and withdraws everybody's key to it. It cannot reach a machine that has already synced it." />
          </StackPanel>
        </Grid>
      </Border>

      <ScrollViewer Grid.Row="1" IsVisible="{Binding HasSelection}">
        <StackPanel Margin="14,14" Spacing="18">

          <!-- The rename form, in place, exactly as the create form on the left is. -->
          <Border Padding="12" CornerRadius="4" BorderThickness="1"
                  BorderBrush="{StaticResource Border}" IsVisible="{Binding IsRenamingVault}">
            <StackPanel Spacing="8">
              <TextBlock Classes="label" Text="RENAME VAULT" />
              <TextBox PlaceholderText="Name" Text="{Binding EditVaultName}" />
              <TextBlock Classes="hint" FontSize="10.5" TextWrapping="Wrap"
                         Text="Everybody who shares this vault sees the new name. Nothing is re-encrypted and no key changes; the name has always been stored in plain text, because a person has to be able to pick a vault before anything is decrypted." />
              <StackPanel Orientation="Horizontal" Spacing="6">
                <Button Classes="accent" Content="SAVE" Command="{Binding SaveVaultNameCommand}"
                        IsEnabled="{Binding !IsBusy}" />
                <Button Classes="ghost" Content="CANCEL" Command="{Binding CancelRenameVaultCommand}" />
              </StackPanel>
            </StackPanel>
          </Border>

          <!--
            The armed confirmation, drawn where the buttons that armed it were. The keychain screen's
            idiom, and for the same reason: there is no modal anywhere in this window.
          -->
          <Border Background="{StaticResource DangerWash}" BorderBrush="{StaticResource DangerSoft}"
                  BorderThickness="1" CornerRadius="4" Padding="12"
                  IsVisible="{Binding IsConfirming}">
            <StackPanel Spacing="8">
              <TextBlock Text="{Binding PendingAction.Question}" FontSize="13" FontWeight="Medium"
                         Foreground="{StaticResource Text}" TextWrapping="Wrap" />
              <TextBlock Classes="hint" FontSize="11.5" TextWrapping="Wrap"
                         Text="{Binding PendingAction.Consequence}" />
              <StackPanel Orientation="Horizontal" Spacing="6">
                <Button Classes="danger" Content="CONFIRM" Command="{Binding ConfirmActionCommand}"
                        IsEnabled="{Binding !IsBusy}" />
                <Button Classes="ghost" Content="CANCEL" Command="{Binding CancelActionCommand}" />
              </StackPanel>
            </StackPanel>
          </Border>

          <!--
            The personal vault, which is the one vault sharing cannot reach. Said here rather than by
            drawing the members section empty: an empty MEMBERS heading over a vault that can never have
            any reads as a feature that has not loaded.
          -->
          <StackPanel Spacing="8" IsVisible="{Binding SelectedIsPersonal}">
            <TextBlock Classes="label" Text="YOURS ALONE" />
            <TextBlock Classes="hint" FontSize="11.5" TextWrapping="Wrap"
                       Text="Nobody can be added to your personal vault, and the server refuses a key grant on one outright — a key wrapped to somebody it will go on refusing to serve would look like sharing and would not be. Make a vault above for the things you want to share, and put them in it." />
          </StackPanel>

          <!-- Members -->

          <StackPanel Spacing="8" IsVisible="{Binding SelectedIsShared}">
            <TextBlock Classes="label" Text="MEMBERS" />

            <!--
              Only ever non-empty for a membership list this screen did not make. Adding somebody to one
              vault and silently adding them to three others is precisely the fact a vault-shaped screen
              is in a position to hide, so it says it instead.
            -->
            <TextBlock Classes="hint" FontSize="11" TextWrapping="Wrap"
                       IsVisible="{Binding HasSharedMembershipWarning}"
                       Text="{Binding SharedMembershipWarning}" />

            <ListBox ItemsSource="{Binding Members}" SelectedItem="{Binding SelectedMember}"
                     Background="Transparent" BorderThickness="0" MaxHeight="240">
              <ListBox.ItemTemplate>
                <DataTemplate x:DataType="vm:VaultMemberRowViewModel">
                  <Grid ColumnDefinitions="*,168,Auto" Margin="0,3">
                    <StackPanel Grid.Column="0" Spacing="2">
                      <TextBlock Text="{Binding Name}" FontSize="13" FontWeight="Medium"
                                 Foreground="{StaticResource Text}" TextTrimming="CharacterEllipsis" />
                      <TextBlock Classes="hint" FontSize="11" Text="{Binding Email}" />
                    </StackPanel>
                    <StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
                      <TextBlock Classes="hint" FontSize="11" Text="{Binding KeyState}"
                                 TextWrapping="Wrap" />
                      <TextBlock Classes="hint" FontSize="10.5" Text="{Binding LastActive}" />
                    </StackPanel>
                    <TextBlock Grid.Column="2" Classes="mono" Text="{Binding Role}" FontSize="10"
                               Foreground="{StaticResource TextFaint}" VerticalAlignment="Center"
                               Margin="10,0,0,0" />
                  </Grid>
                </DataTemplate>
              </ListBox.ItemTemplate>
            </ListBox>

            <!--
              Buttons and a command rather than a selector bound to the role, which is the choice the
              key editor and the category rail already make and for the reason they record: a selector
              moves its own highlight before anything can refuse, so it can end up showing a role
              nobody was given. OWNER is absent because it is not a role that can be assigned —
              handing the vault over is its own act, with its own confirmation.
            -->
            <StackPanel Spacing="6" IsVisible="{Binding CanAdministerSelected}">
              <TextBlock Classes="label" Text="SET THE SELECTED MEMBER'S ROLE" />
              <StackPanel Orientation="Horizontal" Spacing="6">
                <Button Classes="flat choice" Content="VIEWER" Command="{Binding ChangeRoleCommand}"
                        CommandParameter="{x:Static contracts:TeamMemberRole.Viewer}"
                        IsEnabled="{Binding !IsBusy}"
                        ToolTip.Tip="May pull this vault and may not push. It does not withdraw a key they already hold." />
                <Button Classes="flat choice" Content="MEMBER" Command="{Binding ChangeRoleCommand}"
                        CommandParameter="{x:Static contracts:TeamMemberRole.Member}"
                        IsEnabled="{Binding !IsBusy}"
                        ToolTip.Tip="May read and change what is in this vault." />
                <Button Classes="flat choice" Content="ADMIN" Command="{Binding ChangeRoleCommand}"
                        CommandParameter="{x:Static contracts:TeamMemberRole.Admin}"
                        IsEnabled="{Binding !IsBusy}"
                        ToolTip.Tip="May also add and remove people, rename the vault, and share its key." />
              </StackPanel>
            </StackPanel>

            <Grid ColumnDefinitions="*,Auto,Auto" IsVisible="{Binding CanAdministerSelected}">
              <TextBox Grid.Column="0" PlaceholderText="colleague@example.com"
                       Text="{Binding NewMemberEmail}" Margin="0,0,6,0" />
              <Button Grid.Column="1" Classes="accent" Content="ADD"
                      Command="{Binding AddMemberCommand}" IsEnabled="{Binding !IsBusy}"
                      ToolTip.Tip="Adds the account that signs in with this address. An address with no account here is refused and says so — ask them to sign in to this server once, which is what creates the account, and then add them." />
              <Button Grid.Column="2" Classes="danger" Content="REMOVE" Margin="6,0,0,0"
                      Command="{Binding RemoveMemberCommand}" IsEnabled="{Binding !IsBusy}"
                      ToolTip.Tip="Removes the selected member and withdraws every key they hold to this vault. It blocks future reads only — anything already on their machine stays there, so rotate the credentials that matter." />
            </Grid>

            <StackPanel Spacing="4" IsVisible="{Binding CanAdministerSelected}">
              <TextBlock Classes="label" Text="THEY ARRIVE AS" />
              <StackPanel Orientation="Horizontal" Spacing="6">
                <Button Classes="flat choice" Content="VIEWER" Classes.active="{Binding AddsAsViewer}"
                        Command="{Binding ChooseNewMemberRoleCommand}"
                        CommandParameter="{x:Static contracts:TeamMemberRole.Viewer}" />
                <Button Classes="flat choice" Content="MEMBER" Classes.active="{Binding AddsAsMember}"
                        Command="{Binding ChooseNewMemberRoleCommand}"
                        CommandParameter="{x:Static contracts:TeamMemberRole.Member}" />
                <Button Classes="flat choice" Content="ADMIN" Classes.active="{Binding AddsAsAdmin}"
                        Command="{Binding ChooseNewMemberRoleCommand}"
                        CommandParameter="{x:Static contracts:TeamMemberRole.Admin}" />
              </StackPanel>
            </StackPanel>

            <TextBlock Classes="hint" FontSize="10.5" TextWrapping="Wrap"
                       IsVisible="{Binding CanAdministerSelected}"
                       Text="Adding somebody lets the server serve them this vault. It does not let them read it: a vault key can only be wrapped by a machine that already holds it, which is what SHARE KEY below does." />
          </StackPanel>

          <Border Height="1" Background="{StaticResource BorderSubtle}" />

          <!-- Who holds the key -->

          <StackPanel Spacing="8">
            <StackPanel Orientation="Horizontal" Spacing="6" IsVisible="{Binding SelectedIsShared}">
              <Button Classes="accent" Content="SHARE KEY" Command="{Binding ShareVaultCommand}"
                      IsEnabled="{Binding !IsBusy}"
                      ToolTip.Tip="Wraps this vault's key to the selected member. Their published key is checked against the server's append-only key log first, and nothing is wrapped if it does not appear there unchanged." />
              <Button Classes="danger" Content="WITHDRAW KEY" Command="{Binding RevokeVaultCommand}"
                      IsEnabled="{Binding !IsBusy}"
                      ToolTip.Tip="Withdraws the selected member's key to this vault. Blocks future reads only." />
            </StackPanel>

            <!--
              Who can open this vault — the design's "shared with" avatars, as names and a state.
              Withdrawn and stale grants stay listed and say which they are, because a list that quietly
              dropped them would show a departed colleague as merely absent rather than as somebody whose
              key was taken away. The dot is Live and means exactly what it says: this person can open
              this vault right now.
            -->
            <TextBlock Classes="label" Text="KEY HOLDERS" />

            <ListBox ItemsSource="{Binding Grants}" Background="Transparent" BorderThickness="0"
                     MaxHeight="150">
              <ListBox.ItemTemplate>
                <DataTemplate x:DataType="vm:VaultGrantRowViewModel">
                  <Grid ColumnDefinitions="10,*" Margin="0,3">
                    <Ellipse Grid.Column="0" Width="6" Height="6" VerticalAlignment="Center"
                             IsVisible="{Binding IsLive}" Fill="{StaticResource Live}" />
                    <StackPanel Grid.Column="1" Spacing="2" Margin="6,0,0,0">
                      <TextBlock Text="{Binding Name}" FontSize="13" FontWeight="Medium"
                                 Foreground="{StaticResource Text}" TextTrimming="CharacterEllipsis" />
                      <TextBlock Classes="hint" FontSize="11" Text="{Binding State}" />
                    </StackPanel>
                  </Grid>
                </DataTemplate>
              </ListBox.ItemTemplate>
            </ListBox>

            <TextBlock Classes="hint" FontSize="10.5" TextWrapping="Wrap"
                       IsVisible="{Binding SelectedIsShared}"
                       Text="Sharing verifies the recipient's key against the key log, which proves this server has been consistent with itself — not that the key is the right person's. Compare the fingerprint with them over a channel this server does not carry before sharing anything that matters." />

            <!--
              Said once, where somebody would otherwise go looking for a DELETE button. There is no call
              for it anywhere in the server, and archiving the membership list behind a vault is refused
              while the vault exists — so a button here would be one that always refuses.
            -->
            <TextBlock Classes="hint" FontSize="10.5" TextWrapping="Wrap"
                       Text="A vault cannot be deleted. Nothing in this product removes one, and the server refuses to archive the membership list behind it while it still exists." />
          </StackPanel>

        </StackPanel>
      </ScrollViewer>

      <TextBlock Grid.Row="1" Classes="hint" FontSize="12" Margin="20" TextWrapping="Wrap"
                 VerticalAlignment="Top" IsVisible="{Binding !HasSelection}"
                 Text="Make a vault on the left, or wait for somebody to add you to one. A vault holds hosts and credentials that a group of people share; its key is what makes those readable, and that key is handed out by people rather than by the server." />

      <Border Grid.Row="2" Padding="14,10" BorderBrush="{StaticResource Border}" BorderThickness="0,1,0,0"
              IsVisible="{Binding Status, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
        <TextBlock Classes="hint" FontSize="11.5" Text="{Binding Status}" TextWrapping="Wrap" />
      </Border>

    </Grid>
  </Grid>
</UserControl>
